SimpleDateFormat Parsing Date with 'Z' Literal
When attempting to parse a date in ISO 8601 format using SimpleDateFormat, it may fail to correctly handle the 'Z' literal, which denotes UTC as the preferred reference point. For instance, parsing the string "2010-04-05T17:16:00Z" using the pattern "yyyy-MM-dd'T'HH:mm:ss" will result in an incorrect local time.
The traditional patterns "yyyy-MM-dd'T'HH:mm:ssz" and "yyyy-MM-dd'T'HH:mm:ssZ" are also不足以解析“ z”字面的日期。这种行为似乎是违反直觉的,因为“ z”字面明确指示UTC。
solutionFor example:
SimpleDateFormat sdf = new SimpleDateFormat(“ yyyy-mm-dd'hh:mm:ssx”); Date date = sdf.parse("2010-04-05T17:16:00Z");
This will parse the date correctly as a UTC time.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
Date date = sdf.parse("2010-04-05T17:16:00Z");
Another alternative is to use the java.time package introduced in Java 8, which provides a more modern and comprehensive date and time API。以下代码使用java.Time解析日期:import java.time.instant; 导入Java.Time.ZonedDateTime; 字符串datestring =“ 2010-04-05T17:16:00z”; instant instant = instant.parse(datestring); ZonedDateTime ZonedDateTime = Instant.Atzone(ZoneId.of(“ Z”)); 此方法消除了对复杂模式或显式时区设置的需求,因为Java.Time作为Java。
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3