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