【问题标题】:Instant to String java.time即时字符串 java.time
【发布时间】:2017-09-19 02:29:55
【问题描述】:

有没有一种简单的方法可以使用java.time 实现System.currentTimeMillis()2017-04-13T19:00:00+08:00

到目前为止,我已经尝试了很多方法,但它要么给出了正确的区域,但使用了错误的语言,或者根本没有给出任何区域。

Instant shanghai= Instant.ofEpochMilli(System.currentTimeMillis());
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL)
    .withZone(ZoneId.of("Asia/Shanghai"));
System.out.println(formatter.format(shanghai));

顺便说一句,可能是因为我使用 Java 8 time API 的次数不够多,没有看到它的美,但我确实觉得它是“用脚画蛇”。

例如,withZone 听起来像是在移动时间结果以适应区域。但它实际上也改变了语言,我认为应该只与Locale有关。

【问题讨论】:

    标签: java-8 datetime-format java-time


    【解决方案1】:

    我建议绕过System.currentTimeMillis(),直接跳入java.time的土地:

    System.out.println(OffsetDateTime.now());
    

    为我打印:2017-09-19T06:07:12.814+01:00

    【讨论】:

    • 遗留系统生成长数据。
    【解决方案2】:

    System.currentTimeMillis() 等方法返回的 long 表示自 epoch 在时间线上描述 Instant(瞬时点)以来的毫秒数,可以使用 Instant.ofEpochMilli(…) 转换为对象表示

    long l = System.currentTimeMillis();
    System.out.println(Instant.ofEpochMilli(l));
    
    2017-09-19T08:17:37.054Z
    

    要将其转换为带偏移量的日期时间,您可以使用OffsetDateTime.ofInstant(…)

    System.out.println(
        OffsetDateTime.ofInstant(Instant.ofEpochMilli(l), ZoneId.of("Asia/Shanghai")));
    
    2017-09-19T16:17:37.054+08:00
    

    请注意,此处不需要格式化程序。

    【讨论】:

      【解决方案3】:

      我终于搞定了ISO8601时间!

      Instant shanghai = Instant.ofEpochMilli(System.currentTimeMillis());
      OffsetDateTime o = OffsetDateTime.ofInstant(shanghai,ZoneId.systemDefault());
      DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
      System.out.println(dtf.format(o));
      

      DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(Instant.now()) 抱怨偏移量有问题之后,在DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(...) 抱怨年份之后......

      【讨论】:

      • 请记住JVM默认时区can be changed without notice, even at runtime。如果您知道输出必须在特定区域(例如Asia/Shanghai),最好使用特定区域名称(而不是systemDefault()),如@Holger's answer中所述
      • @Hugo 我对新时间 api 感到困惑,例如如何更改其区域,以及如何更改其语言,或区域和语言环境之间的差异。似乎 Holger 对 OffsetDateTime 所做的事情,在使用 DateTimeFormatter 时也会改变语言。你看,它们都指定了一个区域,但行为不一致。
      • 区域设置指定语言敏感数据(例如,如果您使用使用 ofLocalizedDateTime 创建的格式化程序,它将使用 JVM 默认区域设置)。但是,日期对象本身没有任何特定于语言的数据。 Holger 只更改了偏移量,格式化程序可能会更改语言
      • java.time API 的一个很好的起点是oracle's tutorial。对于语言环境,有another tutorial
      • 但基本上 OffsetDateTime 仅具有对应于日期/时间和偏移量的值。 DateTimeFormatter 可以将这些值格式化为不同的格式,包括不同的语言。但是价值观本身并没有改变,只是他们的表现。示例:值等于2017-09-19T16:17:37.054+08:00 的OffsetDateTime 可以有多种格式,例如September 19th 201719/09/2017 16:17 等。值(日期)始终相同,它是 OffsetDateTime 的一部分,但格式不同,可以通过 DateTimeFormatter 进行更改
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-01
      • 2018-10-22
      • 1970-01-01
      • 2011-12-16
      • 2018-08-16
      • 2015-09-10
      • 1970-01-01
      相关资源
      最近更新 更多