Java 8 Date API-获取一个月中的总星期数 [英] Java 8 Date API - Get total number of weeks in a month

查看:442
本文介绍了Java 8 Date API-获取一个月中的总星期数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Kotlin函数来获取一个月中的总周数

I have a Kotlin function to get the total number of weeks in a month

代码

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)

However this is using a mix of the old Java date/time APIs (Date and Calendar) and the new APIs (Instant)

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

How would I achieve the same result, using just the new APIs?

推荐答案

您可以尝试以下几行:

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

这篇关于Java 8 Date API-获取一个月中的总星期数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆