java - 使用java日历获取一年中的一周,星期日作为一周的第一天

标签 java calendar

我正在尝试为我们的财务部门生成一些代码,他们需要一个字段来为他们提供一年中的当前周,但基于星期日作为一周的第一天。因此,例如 01-25-16 (MM-dd-yyyy) 将是第 4 周。但是,当我使用 java.util.Calendarcalendar.setFirstDayOfWeek 尝试它时周日,它告诉我这是第 5 周,因为它似乎从 12 月底到 1 月 3 日算作第 1 周。

这是我到目前为止编写的代码:

private static int getWeekOfYearBySunday(DateTime dt){
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(dt.getMillis());
    calendar.setFirstDayOfWeek(Calendar.SUNDAY);

    return calendar.get(Calendar.WEEK_OF_YEAR);
}

这会返回周数 5,即使如果一周的开始时间是星期日,它应该是 4。

最佳答案

您必须更改 minimalDaysInFirstWeek,请参阅 Calendar#setMinimalDaysInFirstWeek(int) :

Sets what the minimal days required in the first week of the year are; For example, if the first week is defined as one that contains the first day of the first month of a year, call this method with value 1. If it must be a full week, use value 7.

另见 GregorianCalendar :

For example, January 1, 1998 is a Thursday. If getFirstDayOfWeek() is MONDAY and getMinimalDaysInFirstWeek() is 4 (ISO 8601 standard compatible setting), then week 1 of 1998 starts on December 29, 1997, and ends on January 4, 1998. The week year is 1998 for the last three days of calendar year 1997. If, however, getFirstDayOfWeek() is SUNDAY, then week 1 of 1998 starts on January 4, 1998, and ends on January 10, 1998; the first three days of 1998 then are part of week 53 of 1997 and their week year is 1997.

但是如果您为您的财务部门编写代码,您应该使用正确的 Locale 创建您的日历而不是更改某些属性,请参阅 Calendar#getInstance(Locale) :

Gets a calendar using the default time zone and specified locale. The Calendar returned is based on the current time in the default time zone with the given locale.

关于java - 使用java日历获取一年中的一周,星期日作为一周的第一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35002981/

相关文章:

iphone - 将 iPhone 日历与您的应用程序同步

java - 在 Java 中向日历添加多天

php - MySQL 可用性日历 - 计算空闲日期的方法?

java - 如果我将tomcat中的java版本更改为最新版本会发生什么

java - 来自 Glassfish 的 HttpClient+SSL

java - 如何在java中将列表字符串列表转换为列表整数列表

javascript - 组件更新但新 Prop 不会呈现到日历事件中

android - 如何在日历日 View 中添加圆形装饰器?

java - 创建子类对象时如何调用抽象类构造函数?

java - 如何摆脱在 Ubuntu 中安装 SikuliX API 所需的 OpenCV