详细 H1>
Answer by greg-449对于问题是正确的(使用仅日期对象作为日期时间值)但不是解决方案。
该答案使用LocalDateTime,它不必要地丢弃有关offset-from-UTC的有价值信息。 LocalDateTime并不代表时间轴上的特定时刻,只是根据调整到特定时区的可能时刻的模糊概念。
+02是offset-from-UTC,意思是“比UTC提前两小时”。所以在UTC中,这个同步时刻的时间是12小时,比14小时少2小时。这确实代表了时间轴上的特定时刻。此偏移量是您使用LocalDateTime而不是OffsetDateTime丢弃的有价值信息。
字符串的格式为SQL格式,接近标准ISO 8601格式。仅使用T替换中间的SPACE。默认情况下,类使用ISO 8601格式,因此无需指定格式设置模式。
String input = "2016-08-18 14:27:15.103+02";
String inputModified = ( " " , "T" );不幸的是,Java 8在解析缩写为一小时的偏移值或在小时和分钟之间省略冒号的偏移值方面存在错误。已在Java 9中修复。但在Java 8中,我们需要调整输入。
// Workaround for Java 8 where 2-digit offset fails parsing. Fixed in Java 9.
int lengthOfAbbreviatedOffset = 3;
if ( ( "+" ) == ( () - lengthOfAbbreviatedOffset ) ) {
// If third character from end is a PLUS SIGN, append ':00'.
inputModified = inputModified + ":00";
}
if ( ( "-" ) == ( () - lengthOfAbbreviatedOffset ) ) {
// If third character from end is a PLUS SIGN, append ':00'.
inputModified = inputModified + ":00";
}现在解析。
OffsetDateTime odt = ( inputModified );转储到控制台。请注意我们如何将+02转换为+02:00。
( "input: " + input + " | inputModified: " + inputModified + " | odt: " + odt );input: 2016-08-18 14:27:15.103+02 | inputModified: 2016-08-18T14:27:15.103+02:00 | odt: 2016-08-18T14:27:15.103+02:00
或者,指定格式模式。使用此格式设置模式时,偏移解析错误不会发生。
DateTimeFormatter f = ( "yyyy-MM-dd HH:mm:" );
OffsetDateTime odt = ( input , f );
数据库 H1>
来自Postgres,您应该将值检索为日期时间对象而不是String。
如果JDBC驱动程序符合JDBC 4.2,则可以调用ResultSet::getObject以获取Instant或OffsetDateTime。如果没有,请调用ResultSet::getTimestamp以获取,然后通过调用Timestamp对象上的toInstant立即转换为。
坚持使用为您的业务逻辑;简单地使用类型,仅用于与数据库交换。