我有一个 MapperUtility 类,需要从发送字符串时间的 Web 服务映射字符串 “Fri Nov 22 2013 12:12:13 GMT+0000 (UTC)”
现在,我使用以下代码将其转换为 LocalDateTime:
String time = "Fri Nov 22 2013 12:12:13 GMT+0000 (UTC)";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("E MMM dd yyyy HH:mm:ssZ");
dtf.withZone(ZoneId.of("UTC"));
LocalDateTime convertedDate = LocalDateTime.parse(time, dtf);
但我在 GMT+0000 (UTC) 开始时遇到异常。 当我删除 GMT 之外的字符时,它起作用了。 将它们转换为日期时间后,我需要将它们转换为长毫秒。 请指教。谢谢。
最佳答案
您可以使用 DateTimeFormatterBuilder
构建这样的模式:
static final DateTimeFormatter DF = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ofPattern("E MMM dd yyyy HH:mm:ss"))
.appendLiteral(" GMT")
.appendOffset("+HHmm", "+0000")
.optionalStart()
.appendLiteral(" (")
.appendZoneId()
.appendLiteral(')')
.optionalEnd()
.toFormatter()
.withLocale(Locale.US);
然后,只需:
String date = "Fri Nov 22 2013 12:12:13 GMT+0000 (UTC)";
long ms = OffsetDateTime.parse(date, DF).toInstant().toEpochMilli(); // 1385122333000
关于java - 如何将这种格式的字符串转换为Java 8时间并转换为长毫秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57521723/