Java 8 Date API - Get total number of weeks in a month

折月煮酒 提交于 2019-12-01 19:46:12
Schidu Luca

You can try something like this pair of lines:

YearMonth currentYearMonth = 
    YearMonth.now( 
        ZoneId.systemDefault() 
    )
;
int weeks = 
    currentYearMonth
    .atEndOfMonth()
    .get(
        WeekFields.ISO.weekOfMonth()
    )
;

You can evaluate the "week of month" of last day of this month, in java:

static int getTotalWeeksInMonth(Instant instant) {
    LocalDate localDate = LocalDate.ofInstant(instant, ZoneId.systemDefault());
    LocalDate lastDayOfMonth = localDate.withDayOfMonth(localDate.lengthOfMonth());
    int lastWeekOfMonth = lastDayOfMonth.get(WeekFields.ISO.weekOfMonth());
    return lastWeekOfMonth;
}

See if this fits you, be careful about what Zone you are actually passing, and about WeekFields.ISO, in some regions it may work fine, but in others it may not:

Instant now = Instant.now();

ZonedDateTime zonedNow = now.atZone(ZoneId.systemDefault());
ZonedDateTime monthEnd = zonedNow.with(TemporalAdjusters.lastDayOfMonth());

System.out.println(monthEnd.get(WeekFields.ISO.weekOfMonth()));

Having an Instant I would convert it to date first:

val date = LocalDateTime.ofInstant(instant, ZoneId.systemDefault())

Then go with either

YearMonth.from(date).atEndOfMonth().get(ChronoField.ALIGNED_WEEK_OF_MONTH)

or

YearMonth.from(date).atEndOfMonth().get(WeekFields.ISO.weekOfMonth())

Complete example:

fun getTotalWeeksInMonth(instant: Instant): Int {
    val date = LocalDateTime.ofInstant(instant, ZoneId.systemDefault())
    return YearMonth.from(date).atEndOfMonth().get(ChronoField.ALIGNED_WEEK_OF_MONTH)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!