我对这个问题很晚了,但我觉得缺少完整的答案,也就是说,如何解释周数可能会有很大差异,具体取决于Locale
.
这个问题似乎需要美国(或类似的Locale
)的设置,它使用 1 作为第一周的最少天数,并将星期日作为一周的第一天。
问题和所有答案均采用默认Calendar
实例,第一周最少有 4 天,每周第一天为星期一。
一个简单的演示程序显示了这一点:
public static void main(String[] args) {
{
System.out.println("--- ISO ---");
Calendar calendar = Calendar.getInstance();
System.out.println("First day of week : " + calendar.getFirstDayOfWeek());
System.out.println("Minimal days in 1st week : " + calendar.getMinimalDaysInFirstWeek());
calendar.set(2012, Calendar.SEPTEMBER, 20);
int wk = calendar.get(Calendar.WEEK_OF_MONTH);
System.out.println("Week of Month : " + wk);
}
{
System.out.println("--- USA ---");
Calendar calendar = Calendar.getInstance(Locale.US);
System.out.println("First day of week : " + calendar.getFirstDayOfWeek());
System.out.println("Minimal days in 1st week : " + calendar.getMinimalDaysInFirstWeek());
calendar.set(2012, Calendar.SEPTEMBER, 20);
int wk = calendar.get(Calendar.WEEK_OF_MONTH);
System.out.println("Week of Month : " + wk);
}
}
这产生了这个输出:
--- ISO ---
First day of week : 2
Minimal days in 1st week : 4
Week of Month : 3
--- USA ---
First day of week : 1
Minimal days in 1st week : 1
Week of Month : 4
结论:
无需手动设置第一周或一周的第一天的最少天数。只要确保您使用的是正确的Locale
.
额外的
Joda time 仅支持 ISO 周。从 Java 8 和新的 time API 开始,您可以这样处理:
LocalDate localDate = LocalDate.of(2012, 9, 20);
TemporalField usWeekOfMonth = WeekFields.of(Locale.US).weekOfMonth();
TemporalField isoWeekOfMonth = WeekFields.ISO.weekOfMonth();
System.out.println("USA week of month " + usWeekOfMonth.getFrom(localDate));
System.out.println("ISO week of month " + usWeekOfMonth.getFrom(localDate));
输出 :
USA week of month 4
ISO week of month 4
甚至在格式化程序中也有支持:
DateTimeFormatter usDateTimeFormatter = DateTimeFormatter.ofPattern("W/MM")
.withLocale(Locale.US);
System.out.println("USA formatter : " + usDateTimeFormatter.format(localDate));
DateTimeFormatter isoDateTimeFormatter = DateTimeFormatter.ofPattern("W/MM");
System.out.println("ISO formatter : " + isoDateTimeFormatter.format(localDate));
输出 :
USA formatter : 4/09
ISO formatter : 3/09