【问题标题】:How to format a ZonedDateTime to a String?如何将 ZonedDateTime 格式化为字符串?
【发布时间】: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


【解决方案1】:

您可以使用 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而忽略它定义的时区?
  • 没关系,我发现我需要使用ZonedDateTime.withZoneSameInstant()...谢谢!
【解决方案2】:

非常感谢以上。在 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))

【讨论】:

    猜你喜欢
    • 2019-05-03
    • 2019-04-27
    • 2020-05-30
    • 1970-01-01
    • 2015-03-26
    • 2018-07-24
    • 2014-04-20
    • 2020-07-30
    相关资源
    最近更新 更多