使用 Java 8 更新的答案
使用Java 8并保持与以前相同的原则(一周的第一天取决于您),您应该考虑使用以下方法:Locale
获取特定属性的第一个和最后一个DayOfWeek
Locale
final DayOfWeek firstDayOfWeek = WeekFields.of(locale).getFirstDayOfWeek();
final DayOfWeek lastDayOfWeek = DayOfWeek.of(((firstDayOfWeek.getValue() + 5) % DayOfWeek.values().length) + 1);
查询本周的第一天和最后一天
LocalDate.now(/* tz */).with(TemporalAdjusters.previousOrSame(firstDayOfWeek)); // first day
LocalDate.now(/* tz */).with(TemporalAdjusters.nextOrSame(lastDayOfWeek)); // last day
示范
请考虑以下事项:class
private static class ThisLocalizedWeek {
// Try and always specify the time zone you're working with
private final static ZoneId TZ = ZoneId.of("Pacific/Auckland");
private final Locale locale;
private final DayOfWeek firstDayOfWeek;
private final DayOfWeek lastDayOfWeek;
public ThisLocalizedWeek(final Locale locale) {
this.locale = locale;
this.firstDayOfWeek = WeekFields.of(locale).getFirstDayOfWeek();
this.lastDayOfWeek = DayOfWeek.of(((this.firstDayOfWeek.getValue() + 5) % DayOfWeek.values().length) + 1);
}
public LocalDate getFirstDay() {
return LocalDate.now(TZ).with(TemporalAdjusters.previousOrSame(this.firstDayOfWeek));
}
public LocalDate getLastDay() {
return LocalDate.now(TZ).with(TemporalAdjusters.nextOrSame(this.lastDayOfWeek));
}
@Override
public String toString() {
return String.format( "The %s week starts on %s and ends on %s",
this.locale.getDisplayName(),
this.firstDayOfWeek,
this.lastDayOfWeek);
}
}
我们可以按如下方式演示它的用法:
final ThisLocalizedWeek usWeek = new ThisLocalizedWeek(Locale.US);
System.out.println(usWeek);
// The English (United States) week starts on SUNDAY and ends on SATURDAY
System.out.println(usWeek.getFirstDay()); // 2018-01-14
System.out.println(usWeek.getLastDay()); // 2018-01-20
final ThisLocalizedWeek frenchWeek = new ThisLocalizedWeek(Locale.FRANCE);
System.out.println(frenchWeek);
// The French (France) week starts on MONDAY and ends on SUNDAY
System.out.println(frenchWeek.getFirstDay()); // 2018-01-15
System.out.println(frenchWeek.getLastDay()); // 2018-01-21
原始 Java 7 答案(已过时)
只需使用:
c.setFirstDayOfWeek(Calendar.MONDAY);
解释:
现在,您一周的第一天已设置为 。此设置取决于您的 .Calendar.SUNDAY
Locale
因此,更好的替代方法是初始化您感兴趣的指定。
例如:Calendar
Locale
Calendar c = GregorianCalendar.getInstance(Locale.US);
...将为您提供当前输出,同时:
Calendar c = GregorianCalendar.getInstance(Locale.FRANCE);
...会给你你预期的输出。