如何将ZonedDateTime格式化为字符串? [英] How to format a ZonedDateTime to a String?
问题描述
我想将ZonedDateTime
转换为("dd/MM/yyyy - hh:mm")
格式的String
.我知道这可以在Joda-Time其他类型中实现,只需使用它们的toString("dd/MM/yyyy - hh:mm")
....但这不适用于ZonedDateTime.toString()
.
I want to convert a ZonedDateTime
to a String
in the format of ("dd/MM/yyyy - hh:mm")
. I know this is possible in Joda-Time other types, just using their toString("dd/MM/yyyy - hh:mm")
....But this doesn't work with ZonedDateTime.toString()
.
我试图在另一个时区打印时间,结果似乎总是一样:
I tried to print the time in another timezone and the result appears to be the same always:
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));
我和洛杉矶不在同一时区.
And I am not in the same timezone as Los Angeles.
找到了如何更改时区:
// Change this:
ZonedDateTime date2 = date.of(date.toLocalDateTime(), la); // incorrect!
// To this:
ZonedDateTime date2 = date.withZoneSameInstant(la);
推荐答案
您可以使用java.time.format.DateTimeFormatter. https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
You can use 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));
这篇关于如何将ZonedDateTime格式化为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!