How do I format a javax.time.Instant as a string in the local time zone?

前端 未结 4 1939
迷失自我
迷失自我 2021-02-03 23:58

How do I format a javax.time.Instant as a string in the local time zone? The following translates a local Instant to UTC, not to the local time zone as I was expec

4条回答
  •  滥情空心
    2021-02-04 01:00

    Answering this question wrt the nearly finished JDK1.8 version

    DateTimeFormatter formatter =
      DateTimeFormatter.ofPattern("yyyyMMddHHmmss").withZone(ZoneId.systemDefault());
    return formatter.format(instant);
    

    The key is that Instant does not have any time-zone information. Thus it cannot be formatted using any pattens based on date/time fields, such as "yyyyMMddHHmmss". By specifying the zone in the DateTimeFormatter, the instant is converted to the specified time-zone during formatting, allowing it to be correctly output.

    An alternative approach is to convert to ZonedDateTime:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
    return formatter.format(ZonedDateTime.ofInstant(instant, ZoneId.systemDefault()));
    

    Both approaches are equivalent, however I would generally choose the first if my data object was an Instant.

提交回复
热议问题