简体   繁体   English

在第 1 周获取 2019 年的第一天 java

[英]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.我尝试在week=1中获取year=2019的第一天,即 01.01.2019,但我得到的是 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();

The Calendar API is broken and crap.日历 API 坏了,废话。 It's been replaced (... because it is broken and crappy) with the new java.time API, which you should use.它已被新的java.time API 替换(...因为它已损坏且糟糕),您应该使用它。 The Calendar API lies (An instance of juCalendar 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'). The Calendar API lies (An instance of juCalendar 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) ?) -如果您需要“它已被替换”之外的原因)。

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 .因为关于“一周何时开始”的规则非常奇怪,新的 API 将所有这些规则封装到 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.您可以基于“minimalDaysInFirstWeek”+“firstDayOfWeek”创建一个,或者您提供一个区域设置,java 将根据它计算出来。 Seems like you wanna go by locale, so let's do that!好像你想要 go 按区域设置,所以让我们这样做!

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!成功!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM