验证字符串中的日期是否是该月的最后一天

Dev*_* QA -1 java groovy

我的输入字符串日期如下:

String date = "1/31/2022";
Run Code Online (Sandbox Code Playgroud)

我正在转换为日期:

SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Run Code Online (Sandbox Code Playgroud)

我如何知道我的日期是否是该月的最后一天?

例如:对于字符串“1/31/2022”,输出应该为 true。2023 年 2 月 2 日,速度应该会很快。

这是在 Jenkins 的 Groovy 中运行,但我相信我也可以使用 java

rzw*_*oot 5

SimpleDateFormat已经过时了。我会使用包装中的现代物品java.time

使用单个字符Md如果不使用前导零填充个位数值。

DateTimeFormatter MY_FORMAT = DateTimeFormatter.ofPattern("M/d/uuuu");

LocalDate x = LocalDate.parse("1/31/2022", MY_FORMAT);
if (x.getDayOfMonth() == x.lengthOfMonth()) {
  // it is the last day of the month
}
Run Code Online (Sandbox Code Playgroud)

  • 输入和格式之间不匹配,应更改“MM”或输入应有前导零。 (2认同)