如何获得上个月的确切第一个日期和时间?
我希望获得上个月第一天的确切日期00:00:00Z。
所以,这是我目前的解决方案:
public static String getStartingDateAndTimeOfLastMonth() {
int dayOfCurrentMonth = ZonedDateTime.now().getDayOfMonth();
return ZonedDateTime.now()
.minusDays(dayOfCurrentMonth - 1)
.minusMonths(1)
.format(DateTimeFormatter.ISO_INSTANT);
}
当我调用方法时:
String startDate = CustomUtilsFunctions.getStartingDateAndTimeOfLastMonth();
System.out.println("startDate: " + startDate);
当前解决方案的输出是:
startDate: 2021-05-01T07:22:10.389Z
如您所见,输出的时间是07:22:10.389Z但是,我不知道将其转换为的最简单方法00:00:00:000Z
所以所需的输出是:
startDate: 2021-05-01T00:00:00.000Z
点:我知道,我可以提取小时,分钟和秒和毫秒时间,然后用minus(),但我相信必须有一个简单的解决方案。
回答
您可以先创建所需的日期,然后将其与设定的时间一起使用来撰写DateTime。根据您的用例,您可以使用LocalDateTime或ZonedDateTime。
LocalDate day = LocalDate.now()
.minusMonths(1)
.withDayOfMonth(1);
ZonedDateTime target = ZonedDateTime.of(day, LocalTime.MIDNIGHT, ZoneId.systemDefault());
System.out.println(target);
另一种选择是使用turncatedTo(如@Thomas 在评论中提到的)
ZonedDateTime target = ZonedDateTime.now()
.minusMonths(1)
.withDayOfMonth(1)
.truncatedTo(ChronoUnit.DAYS)
.withZoneSameLocal(ZoneId.of("UTC")); // optional depending on your case
回答
您可以使用 a (如本月)并减去一个月以获得最后一个月,而不是使用今天作为基础。然后开始它的第一天。以 UTC 格式执行所有操作,然后根据需要进行格式化:java.time.YearMonth
public static String getStartingDateAndTimeOfLastMonth() {
// get the current month and subtract one to get the last
YearMonth lastMonth = YearMonth.now().minusMonths(1);
// then return its first day
return lastMonth.atDay(1)
// at the beginning of the day in UTC
.atStartOfDay(ZoneOffset.UTC)
// formatted as desired
.format(
DateTimeFormatter.ofPattern(
"uuuu-MM-dd'T'HH:mm:ss.SSSX",
Locale.ENGLISH
)
);
}
今天(2021 年 6 月 10 日)输出:
2021-05-01T00:00:00.000Z
注意:ZonedDateTime如果它们为零,则默认格式省略秒和秒的分数。
如果你没问题2021-05-01T00:00Z,你可以更换
.format(
DateTimeFormatter.ofPattern(
"uuuu-MM-dd'T'HH:mm:ss.SSSX",
Locale.ENGLISH
)
);
用简单的.toString();。