我想将 ZonedDateTime
转换为 String
格式为 ("dd/MM/yyyy - hh:mm")
。我知道这在 Joda-Time 其他类型中是可能的,只需使用它们的 toString("dd/MM/yyyy - hh:mm")
….但这不适用于 ZonedDateTime.toString()
。
如何将 ZonedDateTime
格式化为 String
?
编辑:
我试图在另一个时区打印时间,结果似乎总是一样的:
ZonedDateTime date = ZonedDateTime.now();
ZoneId la = ZoneId.of("America/Los_Angeles");
ZonedDateTime date2 = date.of(date.toLocalDateTime(), la);
// 24/02/2017 - 04:53
System.out.println(DateTimeFormatter.ofPattern("dd/MM/yyyy - hh:mm").format(date));
// same result as the previous one
// 24/02/2017 - 04:53
System.out.println(DateTimeFormatter.ofPattern("dd/MM/yyyy - hh:mm").format(date2));
而且我和洛杉矶不在同一个时区。
编辑 2:
找到了如何更改时区:
// Change this:
ZonedDateTime date2 = date.of(date.toLocalDateTime(), la); // incorrect!
// To this:
ZonedDateTime date2 = date.withZoneSameInstant(la);
原文由 Michel Feinstein 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以使用 java.time.format.DateTimeFormatter。 https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
这里有一个例子