【问题标题】:How to get the seconds difference between now() and TimeStamp with microseconds (2020-10-06T08:52:54.3556219Z) and using Java 8?如何使用微秒(2020-10-06T08:52:54.3556219Z)和使用 Java 8 获得 now() 和 TimeStamp 之间的秒差?
【发布时间】:2020-10-06 09:02:25
【问题描述】:

我想计算我在使用 Java 8 的响应中收到的当前时间和时间戳之间的差异,以微秒 (2020-10-06T08:52:54.3556219Z) 为单位,请告知。我已经使用了以下,但我没有得到任何具体的解决方案,因此在这里问!

  1. 本地日期时间
  2. 分区日期时间
  3. SimpleDateFormat

【问题讨论】:

  • 你应该使用Instant
  • 我已经尝试过 Instant 并再次尝试如下,希望它正确:timestamp = Instant.parse(payload.getTimestamp());//2020-10-06T10:05:45.027416200Z now_timestamp = Instant.now();//2020-10-06T10:05:45.034Z diffInNanos = Math.abs(now_timestamp.compareTo(timestamp)); // NANO SECONDS diffInMicros = diffInNanos / 1000; // MICRO SECONDS diffInMillis = diffInMicros / 1000; // MILLI SECONDS diffInSeconds = diffInMillis / 1000; // SECONDS assertThat(diffInSeconds < acceptableLimit)
  • 最后,上面例子中的diffInSeconds值是'0.0065837996'。
  • compareTo 未指定给您带来不同。例如,您可以使用Instant.parse("2020-10-06T08:52:54.3556219Z").until(Instant.now(), ChronoUnit.SECONDS)
  • 如何将“2020 年 10 月 6 日星期二 13:42:02 GMT”解析为 Instant?

标签: date time java-8 response difference


【解决方案1】:

您可以使用Instant 并调用.getEpochSecond() 来获取秒数,然后计算秒差

Instant dateTime = Instant.parse("2020-10-06T10:05:45.027416200Z");     
Instant nowDateTime = Instant.now(); // 2020-10-06T10:44:23.173333200Z
long diffSeconds = nowDateTime.getEpochSecond() - dateTime.getEpochSecond();

输出:2318

【讨论】:

    猜你喜欢
    • 2017-06-24
    • 1970-01-01
    • 2017-11-06
    • 1970-01-01
    • 1970-01-01
    • 2011-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多