tl;博士
您最初的问题是 +1000 与 +0100 的拼写错误。尽管如此,以下所有建议仍然适用。您正在使用应该避免使用的糟糕的旧类。
OffsetDateTime.parse(
"2018-12-04T22:22:01+1000" , // Input in standard ISO 8601, with the COLON omitted from the offset as allowed by the standard but breaking some libraries such as `OffsetDateTime.parse`.
DateTimeFormatter.ofPattern(
"uuuu-MM-dd'T'HH:mm:ssX"
)
) // Returns a `OffsetDateTime` object.
.toInstant() // Adjust into UTC. Returns an `Instant` object. Same moment, different wall-clock time.
.atZone( // Adjust from UTC to some time zone. Same moment, different wall-clock time.
ZoneId.of( "Europe/Brussels" )
) // Returns a `ZonedDateTime` object.
.toString() // Generate text representing this `ZonedDateTime` object in standard ISO 8601 format but wisely extending the standard by appending the name of the time zone in square brackets.
18-12-04T13:22:01+01:00[欧洲/布鲁塞尔]
避免使用旧的日期时间类
您正在使用与最早版本的 Java 捆绑在一起的糟糕的旧日期时间类。多年前被 java.time 类取代。
使用适当的时区
仅供参考,CET 不是实时时区。
以continent/region 的格式指定proper time zone name,例如America/Montreal、Africa/Casablanca 或Pacific/Auckland。切勿使用 2-4 个字母的缩写,例如 EST 或 IST,因为它们不是真正的时区,没有标准化,甚至不是唯一的 (!)。
ZoneId z = ZoneId.of( "America/Montreal" ) ;
您可能指的是时区,例如 Europe/Brussels、Europe/Paris、Europe/Berlin、Africa/Tunis 或 Europe/Oslo。
ISO 8601
您的输入字符串2018-12-04T22:22:01+1000 采用标准格式,由ISO 8601 定义。
最后一部分+1000 是offset-from-UTC,表示比UTC 提前十小时。所以这个值是用于人们使用的挂钟时间是太平洋的某个地区,例如时区Australia/Lindeman。
不要缩写偏移符号
该字符串+1000 是偏移量的缩写,省略了小时和分钟(以及秒,如果有)之间的冒号字符分隔符。虽然标准允许这种省略,但我建议始终包括冒号:2018-12-04T22:22:01+10:00。根据我的经验,一些库和协议在遇到此类字符串时会中断。并且包含冒号使字符串对人类来说更具可读性。
OffsetDateTime
确实,默认情况下用于解析此类标准字符串的java.time.OffsetDateTime 类在这方面存在错误,即在省略冒号时无法解析。讨论于:
解决方法:
OffsetDateTime odt =
OffsetDateTime.parse(
"2018-12-04T22:22:01+1000" ,
DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ssX" )
)
;
参见代码示例running live at IdeOne.com。
odt.toString(): 2018-12-04T22:22:01+10:00
通过提取Instant 对象将该值调整为UTC。根据定义,Instant 始终采用 UTC。
Instant instant = odt.toString() ;
instant.toString(): 2018-12-04T12:22:01Z
最后,我们可以调整到您自己的地域时区。
CET 我假设您的意思是 Europe/Paris 这样的时区。
ZoneId z = ZoneId.of( "Europe/Paris" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
当调用ZonedDateTime::toString 时,会以标准 ISO 8601 格式生成文本,但明智地扩展标准以将时区名称附加在方括号中。
zdt.toString(): 2018-12-04T13:22:01+01:00[Europe/Paris]
所有三个这些对象(odt、instant 和zdt)都指向同一时刻,即时间轴上的同一点。他们唯一的区别是挂钟时间。如果在澳大利亚、法国和冰岛(始终使用 UTC)的电话会议中,三个人同时抬起头来从挂在他们当地墙上的各自时钟上读取当前时刻,他们会同时读取三个不同的值。
查看所有代码run live at that IdeOne.com page。
关于java.time
java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.Date、Calendar 和 SimpleDateFormat。
Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。
要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310。
您可以直接与您的数据库交换 java.time 对象。使用符合JDBC 4.2 或更高版本的JDBC driver。不需要字符串,不需要java.sql.* 类。
从哪里获得 java.time 类?
ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是未来可能添加到 java.time 的试验场。您可以在这里找到一些有用的类,例如Interval、YearWeek、YearQuarter 和more。