【发布时间】:2020-09-27 08:51:32
【问题描述】:
我想使用 Java Time API 获取中欧夏令时间 (CEST) 并正确格式化。我有以下代码:
LocalDateTime localDateTime= LocalDateTime.now();
DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
localDateTime.format(myFormatObj);
ZoneId europeBerlin = ZoneId.of("Europe/Berlin");
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, europeBerlin);
命令zonedDateTime.toString()离开到以下输出:
2020-09-27T08:42:33.660+02:00[Europe/Berlin]
但我希望在 DateTimeFormatter 中获得之前指定的输出(“dd-MM-yyyy HH:mm:ss”)。我已经将 localDateTime 格式化为这种格式,现在我只想获取 CEST 时间。我怎样才能做到这一点?我会很感激每一条评论。
【问题讨论】:
-
如果您想使用分区时间,请使用
ZonedDateTime。要将其转换回LocalDateTime,请致电ZonedDateTime::toLocalDateTime。 -
感谢图灵的评论。对我来说,我使用的是哪个课程并不重要。我只想按照我在代码中指定的方式格式化 CEST 时间 ("dd-MM-yyyy HH:mm:ss")
-
我曾经使用过 SimpleDateFormat。我刚刚读到使用 Java Time API 会更好。所以我想这会很好,如果我可以坚持 Java Time API 并且如果可能的话不使用 ZonedTime。但总的来说,如果更好的话,我也可以使用 ZonedTime
-
这能回答你的问题吗? String to ZonedDateTime is changing format
-
您只需要
String formattedDateTime = zonedDateTime.format(myFormatObj);。
标签: java time date-formatting