Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
588 views
in Technique[技术] by (71.8m points)

calendar - Get first day of 2019 in week 1 java

I try to get the first day of the year=2019 in week=1, which is 01.01.2019, but what i get is 31.12.2018. How come and how to solve this? Here is my code:

    Calendar cal = Calendar.getInstance();
    cal.setFirstDayOfWeek(Calendar.MONDAY);               
    cal = this.resetCalendarTime(cal);
    cal.set(Calendar.WEEK_OF_YEAR, Integer.parseInt(*week*));
    cal.set(Calendar.YEAR, *year*);

    cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
    LocalDateTime dptbg = cal.toInstant().atZone("Europe/Berlin").toLocalDateTime();
question from:https://stackoverflow.com/questions/66047271/get-first-day-of-2019-in-week-1-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...