【问题标题】:Use java.time to replace time part in the time instant使用 java.time 替换时间瞬间的时间部分
【发布时间】:2016-12-02 14:14:34
【问题描述】:

我想改变瞬间:

Instant instant = Instant.parse("2016-03-23T17:14:00.092812Z");
LocalTime newTime = LocalTime.parse("12:34:45.567891");
instant.with(newTime);

我希望得到一个具有相同日期但新时间的瞬间,即 2016-03-23 12:34:45.567891。

但它会抛出异常:

java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: NanoOfDay
    at java.time.Instant.with(Instant.java:720)
    at java.time.Instant.with(Instant.java:207)
    at java.time.LocalTime.adjustInto(LocalTime.java:1333)
    at java.time.Instant.with(Instant.java:656)

任何想法如何解决?

【问题讨论】:

  • 将时间设置在瞬间没有多大意义。您需要一个时区来设置时间。将 Instant 转换为 ZonedDateTime,选择时区。然后在 ZonedDateTime 上设置时间。然后将 ZonedDateTime 转换为 Instant。
  • @WilliMentzel 我在真实代码中没有字符串。我在这里解析它只是为了重现最少的代码。日期时间算术的字符串操作看起来很笨拙。

标签: java time java-8


【解决方案1】:

Instant 没有本地日历日期或本地时间的概念。 它的方法 toString() 描述了 UTC 时间线上在偏移 UTC+00:00 的日期和时间方面的时刻,但它仍然是一个时刻,而不是具有本地上下文的信息。

但是,您可以使用以下转换。转换为本地时间戳,操作本地时间戳,然后转换回瞬间/时刻。 看到转换取决于具体的时区非常重要。

Instant instant = Instant.parse("2016-03-23T17:14:00.092812Z");
LocalTime newTime = LocalTime.parse("12:34:45.567891");

// or choose another one, the conversion is zone-dependent!!!
ZoneId tzid = ZoneId.systemDefault(); 
Instant newInstant =
    instant.atZone(tzid).toLocalDate().atTime(newTime).atZone(tzid).toInstant();
System.out.println(newInstant); // 2016-03-23T11:34:45.567891Z (in my zone Europe/Berlin)

【讨论】:

    【解决方案2】:

    将时间设置在瞬间没有多大意义。您需要一个时区来设置时间。将 Instant 转换为 ZonedDateTime,选择时区。然后在 ZonedDateTime 上设置时间。然后将 ZonedDateTime 转换为 Instant:

    假设时间是 UTC 时区:

    Instant instant = Instant.parse("2016-03-23T17:14:00.092812Z");
    LocalTime newTime = LocalTime.parse("12:34:45.567891");
    ZonedDateTime dt = instant.atZone(ZoneOffset.UTC);
    dt = dt.with(newTime);
    instant = dt.toInstant();
    System.out.println("instant = " + instant);
    // prints 2016-03-23T12:34:45.567891Z
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-19
      • 2022-11-14
      • 2016-01-02
      • 2020-10-22
      • 1970-01-01
      • 1970-01-01
      • 2016-05-11
      • 1970-01-01
      相关资源
      最近更新 更多