The Calendar API is broken and crap. It's been replaced (... because it is broken and crappy) with the new java.time
API, which you should use. The Calendar API lies (An instance of j.u.Calendar
isn't a calendar at all. It's some weird amalgamation of solarflares time and human appointment time, the API isn't very java like at all (.set(someIntegerConstant, whatnow)
?) - in case you need reasons beyond 'it was replaced').
Because the rules about 'when does the week start' are so bizarre, the new API encapsulates all these rules into an instance of the class WeekFields
. You can create one either based on 'minimalDaysInFirstWeek' + 'firstDayOfWeek', or you provide a locale and java will figure it out based on that. Seems like you wanna go by locale, so let's do that!
public LocalDate getFirstDayInYearInFirstWeek(int year, Locale locale) {
WeekFields wf = WeekFields.of(locale);
LocalDate firstDayOfYear = LocalDate.of(year, 1, 1);
LocalDate firstDayOfFirstWeek = firstDayOfYear
.with(wf.weekOfYear(), 1)
.with(wf.dayOfWeek(), 1);
return firstDayOfFirstWeek.isBefore(firstDayOfYear) ?
firstDayOfYear : firstDayOfFirstWeek;
}
let's try it:
System.out.println(getFirstDayInYearInFirstWeek(2019, Locale.GERMANY));
> 2019-01-01
System.out.println(getFirstDayInYearInFirstWeek(2016, Locale.GERMANY));
> 2016-01-04
success!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…