首页 > 解决方案 > Java中下个月的最后日期

问题描述

如何在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);
}

标签: javadatelocaldate

解决方案


该类TemporalAdjusters包含一些静态TemporalAdjuster的,其中lastDayOfMonth(),所以你可以做

LocalDate.now()
         .plusMonth(1)
         .with(TemporalAdjusters.lastDayOfMonth());

推荐阅读