【发布时间】:2017-07-14 12:05:12
【问题描述】:
我想将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);
【问题讨论】:
-
你在使用 jdk8 java.time.ZonedDateTime 吗?
-
是的,我想是的......
-
使用 ZonedDateTime 类型的 format() 方法
-
使用符号“h”(小写字母)是一个严重的错误。要么将它与 am/pm 结合使用,因为它是 12 小时字段,要么使用符号“H”(大写字母)表示 24 小时字段。
标签: java string java-time zoneddatetime