【问题标题】:Scala - How to convert LocalDateTime to ZonedDateTime formatted without GMT postfix?Scala - 如何将 LocalDateTime 转换为无 GMT 后缀格式的 ZonedDateTime?
【发布时间】:2020-02-25 03:21:02
【问题描述】:

我想在 GMT 中获取 LocalDateTime,所以用 ZonedDateTime 包装它。

gmtZoneTime 以以下格式返回:2019-10-29T00:00Z[GMT] 而我需要它是:2019-10-29T00:00:00.000+0000

我应该如何正确地将localDateTime 转换为 GMT ZonedDateTime?

val currentDate:LocalDate = java.time.LocalDate.now
val localDateTime: LocalDateTime = currentDate.atStartOfDay
val gmtZoneTime: ZonedDateTime = localDateTime.atZone(ZoneId.systemDefault()).withZoneSameInstant(ZoneId.of("GMT"))

【问题讨论】:

    标签: java scala datetime time


    【解决方案1】:

    您需要格式化ZonedDateTime

    第一种方法是使用预定义的格式化程序,例如:java.time.format.DateTimeFormatter.ISO_OFFSET_DATE_TIME,但是对于GMT,它显示“Z”而不是“+0000”(默认行为,其他偏移量显示为“+0100”等)

    所以第二个是创建自己的格式化程序,例如: java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ")

    然后用它来格式化ZonedDateTime,比如gmtZoneTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ")) 所以你会得到如下结果:

    2019-10-28T23:00:00+0000
    

    【讨论】:

      【解决方案2】:

      首先您的代码不正确。当我刚才在我的时区(欧洲/哥本哈根)运行它时,我得到了

      2019-10-29T23:00Z[GMT]

      我认为您不打算在 GMT 时间 23:00。

      其次,您可能会将 GMT 或 UTC 视为偏移量(与 UTC 相差为零),因此在当时使用 OffsetDateTIme 比使用 ZonedDateTime 更正确。这也消除了您不需要的后缀。在 Java 中(这是我能写的全部):

          LocalDate currentDate = LocalDate.now(ZoneOffset.UTC);
          OffsetDateTime gmtZoneTime = currentDate.atStartOfDay(ZoneOffset.UTC)
                  .toOffsetDateTime();
          System.out.println(gmtZoneTime);
      

      刚刚运行时的输出:

      2019-10-30T00:00Z

      编辑:您可以放心地将 UTC 和 GMT 视为同义词,因为 java.time 会这样做(尽管严格来说它们可能相差一秒)。

      我假设您还想要 UTC 日期,因此将其作为参数传递给 LocalDate.now()。如果您想要某个其他时区的日期,请将该时区传递给LocalDate.now(),以便从代码中清楚您得到什么。

      如果您想在问题中使用该特定格式,pezetem 在您需要格式化为字符串的其他答案中是正确的:

          DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSxx");
          String formattedGmtTime = gmtZoneTime.format(formatter);
          System.out.println(formattedGmtTime);
      

      2019-10-30T00:00:00.000+0000

      不过,这对我来说似乎很罗嗦。我至少会省略毫秒,因为我们知道它们是 0,也可能是秒。在不知道您的确切业务案例的情况下说。

      链接: Difference between UTC and GMT

      【讨论】:

      • 您可以放心地将 UTC 和 GMT 视为同义词。请看我的小修改。
      猜你喜欢
      • 2018-09-25
      • 2020-01-11
      • 2017-05-31
      • 2020-12-13
      • 2019-01-21
      • 1970-01-01
      • 2018-04-13
      • 2021-12-09
      • 1970-01-01
      相关资源
      最近更新 更多