首页 > 解决方案 > 使用 java.time.temporal.ChronoUnit 时出现 DateTimeParseException

问题描述

我对堆栈溢出和编程都是新手。我正在尝试使用 Java 8 来查找时间戳值和当前时间戳值之间的时间差。

以下是我的 Scala 代码的代码片段:

println(ChronoUnit.MILLIS.between(Instant.parse("1534274986"), Instant.now()))

它工作正常,直到我有一个测试用例,其中 Human DateTime 的时代归结为08/14/18 19:06:17. 在这种情况下,我收到一个错误:

Execution exception[[DateTimeParseException: Text '08/14/18 19:06:17' could not be parsed at index 0]]

请帮助我理解为什么我会收到这样的错误。谢谢你。

标签: javascaladatetimedatetime-format

解决方案


默认情况下,.parse()方法LocalDateTime相当有限。这就是您遇到上面发布的错误的原因。但是您可以通过在两者之间使用 FormatterBuilder 设计和应用您自己的特定格式化程序来解决此问题:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
  .appendPattern("MM/dd/yy[ HH:mm:ss]")
  .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
  .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
  .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
  .toFormatter();

LocalDateTime localDateTime1 = LocalDateTime.parse("08/14/18 19:06:17", formatter);
LocalDateTime localDateTime2 = LocalDateTime.parse("08/14/18 19:08:19", formatter);

System.out.println(ChronoUnit.MILLIS.between(localDateTime1, localDateTime2));

// Result: 122000 ms

您也可以将格式化时间与当前本地时间进行比较:

    LocalDateTime currentDateTime = LocalDateTime.now();
    System.out.println(ChronoUnit.MILLIS.between(localDateTime1, currentDateTime));

如果您更喜欢使用,您可以轻松地从上面解析的实例Instant中创建自己的实例:LocalDateTime

    import java.time.*;

    LocalDateTime currentDateTime = LocalDateTime.now();
    ZoneId zoneId = ZoneId.of("US/Eastern");
    ZonedDateTime zonedDateTime = ZonedDateTime.of(currentDateTime, zoneId);
    Instant instant = zonedDateTime.toInstant();

推荐阅读