java - 使用 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]]
请帮助我理解为什么我会收到这样的错误。谢谢你。
解决方案
默认情况下,.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();
推荐阅读
- node.js - 自发布的 NPM 包添加时不导入任何内容
- ruby-on-rails - 如何让 Sendgrid Inbound Parse Webhook 在生产中的 rails 应用程序中工作?
- python - 将每个实例掩码合并回原始图像 Python
- node.js - 如何在构建期间创建带有转储的 postgreSQL 数据库以在 gitlab-CI 中启动单元测试?
- ios - 如何使用带有 react-native-camera 的默认 iOS 相机控件
- swift - 路径中的 SwiftUI UIImage 不可见
- scala - Doobie for Scala / Play 框架中的事务
- loops - TestCafe 循环遍历元素并检查 Set 中是否存在类
- javascript - 为什么当我更新商品数量时,循环遍历购物车商品并返回商品数量的 Vuex getter 不更新?
- python - 使用布尔数组的逐项总和作为包含的“或”