Start and end date of a current month

后端 未结 12 2214
我寻月下人不归
我寻月下人不归 2020-11-29 03:08

I need the start date and the end date of the current month in Java. When the JSP page is loaded with the current month it should automatically calculate the start and end d

12条回答
  •  攒了一身酷
    2020-11-29 04:08

    For Java 8+, below method will given current month first & last dates as LocalDate instances.

    public static LocalDate getCurrentMonthFirstDate() {
        return LocalDate.ofEpochDay(System.currentTimeMillis() / (24 * 60 * 60 * 1000) ).withDayOfMonth(1);
    }
    
    public static LocalDate getCurrentMonthLastDate() {
        return LocalDate.ofEpochDay(System.currentTimeMillis() / (24 * 60 * 60 * 1000) ).plusMonths(1).withDayOfMonth(1).minusDays(1);
    }
    

    Side note: Using LocalDate.ofEpochDay(...) instead of LocalDate.now() gives much improved performance. Also, using the millis-in-a-day expression instead of the end value, which is 86400000 is performing better. I initially thought the latter would perform better than the the expression :P

提交回复
热议问题