【发布时间】:2019-11-27 09:03:04
【问题描述】:
如何在 Java 中获取下个月的最后一个日期?
背景:我有项目,用户只对订单感兴趣,应该在下个月底完成。所以我需要获取下个月的最后一个日期并与订单结束日期进行比较,如果订单结束日期小于下个月的最后一个日期,则意味着应该选择该订单。
我的解决方案是这样的,但不确定是不是最好的:
public static boolean shouldCompleteByNextMonth(final Date endDate) {
final LocalDate now = LocalDate.now(); // Get current local date.
final LocalDate nextMonth = now.plusMonths(1); // Get next month.
final int daysInNextMonth = nextMonth.lengthOfMonth(); // Get the length of next month
final LocalDate lastLocalDateOfNextMonth = nextMonth.plusDays(daysInNextMonth - now.getDayOfMonth()); // Get the last Date of next month
// default time zone
final ZoneId defaultZoneId = ZoneId.systemDefault();
// convert last locale date to a Date
final Date lastDateOfNextMonth = Date.from(lastLocalDateOfNextMonth.atStartOfDay(defaultZoneId).toInstant());
// Compare with the given endDate, if last date of next month is after it, return true, else, return false.
return lastDateOfNextMonth.after(endDate);
}
【问题讨论】:
-
最好给出自己的解决方案,这样我们就可以讨论它而不是寻求解决方案。我建议关闭此问题,因为idownvotedbecau.se/noattempt
-
得到两个月的第一个然后减去一天会更简单吗?