How to parse date from string with year and week using java.time

后端 未结 3 1638
南旧
南旧 2020-12-17 02:00

In old java I can do it in that way:

System.out.println(new SimpleDateFormat(\"yyyy w\", Locale.UK).parse(\"2015 1\"));
// shows Mon Dec 29 00:00:00 CET 2014         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-17 02:19

    Direct answer and solution:

    System.out.println( 
      LocalDate.parse("2015 1", 
        new DateTimeFormatterBuilder().appendPattern("YYYY w")
        .parseDefaulting(WeekFields.ISO.dayOfWeek(), 1)
        .toFormatter()));
    // output: 2014-12-29
    

    Explanations:

    a) You should use Y instead of y because you are interested in ISO-8601-week-date, not in year-of-era.

    b) A calendar date cannot be formed by just giving a (week-based) year and a week-number. The day of week matters to determine the day within the specified calendar week. The predefined formatter for week-dates requires the missing day-of-week. So you need to construct a specialized parser using the builder-pattern. Then it is necessary to tell the parser what day of week is wanted - via the method parseDefaulting().

    c) I insist (and defend JSR-310 here) on saying that the question when a week starts is not a calendar issue but a country-dependent issue. US and France (as example) use the same calendar but have different views how to define a week. ISO-8601-standard can be applied using the explicitly ISO-referring field WeekFields.ISO.dayOfWeek(). Attention: Testing has revealed that using ChronoField.DAY_OF_WEEK together with Locale.ROOT does not always seem to guarantee ISO-week-behaviour as indicated in my first version of this answer (the reasons are not yet clear for me - a close view of the sources seems to be necessary to enlighten the unintuitive behaviour).

    d) The java-time-package does it well - with the exception that Monday is just specified as number 1. I would have preferred the enum. Or use the enum and its method getValue().

    e) Side notice: SimpleDateFormat behaves leniently by default. The java-time-package is stricter and rejects to invent a missing day-of-week out of thin air - even in lenient mode (which is in my opinion rather a good thing). Software should not guess so much, instead the programmer should think more about what day-of-week is the right one. Again here: The application requirements will probably differ in US and France about the right default setting.

提交回复
热议问题