我收到一个字符串,其中日期的形式为"2020-05-16 01:00+0200"
.我需要将其解析为 DateTime 对象,但我找不到正确的模式,即DateTimeFormat.forPattern("yyyy-MM-dd HH:mm????");
如何包含字符串中的"+0200"? 另外,有没有办法从日期时间中提取偏移量?
谢谢和布格斯。
String dateStringToParse = "2020-05-16 01:00+0200";
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mmZ")
.withOffsetParsed();
DateTime dt = DateTime.parse(dateStringToParse, formatter);
System.out.println(dt);
输出为:
2020-05-16T01:00:00.000+02:00
Joda-Time 的标准行为是解析到您的默认时区。对withOffsetParsed()
的调用可确保字符串的偏移量保留在解析的DateTime
中。
DateTimeFormat
的文档说模式字母Z
:
Symbol Meaning Presentation Examples ------ ------- ------------ ------- Z time zone offset/id zone -0800; -08:00; America/Los_Angeles
和:
区域:">Z"输出偏移量,不带冒号,...
提取偏移量:
DateTimeZone z = dt.getZone();
System.out.println(z);
+02:00
链接:DateTimeFormat
文档