Java 8 Date API-获取一个月中的总星期数

时间:2019-01-04 15:24:26

标签: java datetime kotlin java-8 java-date

我具有Kotlin函数,可以获取一个月中的总周数

代码

fun getTotalWeeksInMonth(instant: Instant): Int {
    val calendar = Calendar.getInstance()
    calendar.time = Date.from(instant)

    return calendar.getActualMaximum(Calendar.WEEK_OF_MONTH)
}

但是,这是结合使用旧的Java日期/时间API(DateCalendar)和新的Java API(Instant

仅使用新的API,我将如何获得相同的结果?

4 个答案:

答案 0 :(得分:4)

您可以尝试以下几行:

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

答案 1 :(得分:1)

您可以使用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;
}

答案 2 :(得分:0)

看看这是否适合您,请注意您实际上通过了什么Zone,并注意WeekFields.ISO,在某些地区可能效果不错,但在其他地区则可能不行:

Instant now = Instant.now();

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

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

答案 3 :(得分:0)

拥有一个Instant,我首先将其转换为日期:

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

然后选择

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

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

完整示例:

fun getTotalWeeksInMonth(instant: Instant): Int {
    val date = LocalDateTime.ofInstant(instant, ZoneId.systemDefault())
    return YearMonth.from(date).atEndOfMonth().get(ChronoField.ALIGNED_WEEK_OF_MONTH)
}