如何将 ZonedDateTime 格式化为字符串?
How to format a ZonedDateTime to a String?
我想将 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);
您可以使用 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));
非常感谢以上。在 scala 中,localDateTime.now 总是 Zulu/UTC 时间。
import java.time.format.DateTimeFormatter
import java.time.LocalDateTime
import java.time.ZoneId
val ny = ZoneId.of("America/New_York")
val utc = ZoneId.of("UTC")
val dateTime = LocalDateTime.now.atZone(utc)
val nyTime = DateTimeFormatter.
ofPattern("yyyy-MMM-dd HH:mm z").
format(dateTime.withZoneSameInstant(ny))
我想将 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);
您可以使用 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));
非常感谢以上。在 scala 中,localDateTime.now 总是 Zulu/UTC 时间。
import java.time.format.DateTimeFormatter
import java.time.LocalDateTime
import java.time.ZoneId
val ny = ZoneId.of("America/New_York")
val utc = ZoneId.of("UTC")
val dateTime = LocalDateTime.now.atZone(utc)
val nyTime = DateTimeFormatter.
ofPattern("yyyy-MMM-dd HH:mm z").
format(dateTime.withZoneSameInstant(ny))