簡體   English   中英

如何在java.time中的模式字符串中格式化日期與時區?

[英]How to format Date with time zone in pattern string in java.time?

我有一個格式化程序的字符串模式

yyyy-MM-dd HH:mm:ss Z

如何使用這種模式解析java.util.Date?

問題是此模式中的時區已經存在。

String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss Z";

DateTimeFormatter.ofPattern(DATE_TIME_FORMAT).format(date.toInstant());

這顯然給了

java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: YearOfEra
    at java.time.Instant.getLong(Instant.java:603)
    at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298)

此處和其他地方的解決方案在格式字符串中沒有時區,並提供以下解決方案:

DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.ofInstant(dateD.toInstant(), ZoneId.systemDefault()))

我可以以某種方式解析它嗎?

Instant沒有時代的概念

支持的字段是:

  • NANO_OF_SECOND
  • MICRO_OF_SECOND
  • MILLI_OF_SECOND
  • INSTANT_SECONDS

您可以使用ZonedDateTime:

ZonedDateTime zdt = date.toInstant().atZone(ZoneOffset.UTC);
String format = DateTimeFormatter.ofPattern(DATE_TIME_FORMAT).format(zdt);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM