如何将ZonedDateTime格式化为String?

mFe*_*ein 38 java string java-time zoneddatetime

我想将a转换ZonedDateTime为a String格式("dd/MM/yyyy - hh:mm").我知道这在Joda-Time其他类型中是可能的,只是使用它们toString("dd/MM/yyyy - hh:mm")....但这不起作用ZonedDateTime.toString().

如何格式化ZonedDateTimeString


编辑:

我试图在另一个时区打印时间,结果似乎总是一样:

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));
Run Code Online (Sandbox Code Playgroud)

而且我和洛杉矶不在同一时区.


编辑2:

找到了如何更改时区:

// Change this:
ZonedDateTime date2 = date.of(date.toLocalDateTime(), la); // incorrect!
// To this:
ZonedDateTime date2 = date.withZoneSameInstant(la);
Run Code Online (Sandbox Code Playgroud)

reo*_*eos 63

您可以使用java.time.format.DateTimeFormatter. https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

这里有一个例子

ZonedDateTime date = ZonedDateTime.now();

System.out.println(DateTimeFormatter.ofPattern("dd/MM/yyyy - hh:mm").format(date));
Run Code Online (Sandbox Code Playgroud)