How to create Java time instant from pattern?

后端 未结 4 985
隐瞒了意图╮
隐瞒了意图╮ 2021-02-01 01:51

Consider a code:

TemporalAccessor date = DateTimeFormatter.ofPattern(\"yyyy-MM-dd\").parse(\"9999-12-31\");
Instant.from(date);

The last line t

4条回答
  •  执笔经年
    2021-02-01 02:25

    The problem isn't the fact that you are using the year 9999. The Instant.MAX field evaluates to the timestamp 1000000000-12-31T23:59:59.999999999Z, so 9999 as a year is fine.

    Dealing with TemporalAccessors instead of the more semantically rich types like LocalDateTime or ZonedDateTime is like using a Map to model an object and its properties instead of writing a class -- you have to assure that the value has the fields (like seconds, nanoseconds, etc) that are expected by something receiving it, rather than depending on formally declared operations in a higher level class to prevent dependencies from going unmet.

    In your case it is likely that the temporal accessor contained the parsed date fields it was given, but didn't have a "seconds" field that the Instant needed. It is best to use the more semantically rich types like LocalDateTime in most instances.

    Since you only have date fields, you should parse it as a date, then add the time fields before converting it to an Instant. Here is one way, using LocalDate to parse the date:

    LocalDate localDate = LocalDate.parse("2016-04-17");
    LocalDateTime localDateTime = localDate.atStartOfDay();
    Instant instant = localDateTime.toInstant(ZoneOffset.UTC);
    

提交回复
热议问题