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
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