简介
使用java.time.Instant
类来解析标准ISO 8601格式的文本,表示UTC中的一个时刻。
Instant.parse( "2010-10-02T12:23:23Z" )
ISO 8601
该格式由ISO 8601标准定义,用于日期时间字符串格式。
以下两种方式:
…默认使用ISO 8601格式进行解析和生成字符串。
通常应避免使用旧的java.util.Date/.Calendar & java.text.SimpleDateFormat类,因为它们往往会造成问题、令人困惑和存在缺陷。如果需要互操作,可以进行转换。
java.time
Java 8及其后续版本中内置了新的
java.time框架。该框架受
Joda-Time启发,由
JSR 310定义,并由
ThreeTen-Extra项目扩展。请注意保留HTML标签。
Instant instant = Instant.parse( "2010-10-02T12:23:23Z" ); // `Instant` is always in UTC.
转换为旧的类。
java.util.Date date = java.util.Date.from( instant ); // Pass an `Instant` to the `from` method.
时区
如果需要,您可以分配一个时区。
ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Define a time zone rather than rely implicitly on JVM’s current default time zone.
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId ); // Assign a time zone adjustment from UTC.
转换。
java.util.Date date = java.util.Date.from( zdt.toInstant() ); // Extract an `Instant` from the `ZonedDateTime` to pass to the `from` method.
Joda-Time
更新:Joda-Time项目现已进入维护模式。团队建议迁移到java.time类。
这是一些Joda-Time 2.8的示例代码。
org.joda.time.DateTime dateTime_Utc = new DateTime( "2010-10-02T12:23:23Z" , DateTimeZone.UTC );
转换为旧类。请注意,在转换过程中分配的时区将丢失,因为j.u.Date无法分配时区。
java.util.Date date = dateTime_Utc.toDate()
时区
如果需要,您可以指定一个时区。
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTime_Montreal = dateTime_Utc.withZone ( zone );
![Table of date-time types in Java, both modern and legacy.](https://istack.dev59.com/XuzUE.webp)
关于java.time
java.time框架内置于Java 8及更高版本。这些类替代了老旧的legacy日期时间类,如java.util.Date
、Calendar
和SimpleDateFormat
。
Joda-Time项目现在处于维护模式,建议迁移到java.time类。
了解更多信息,请参阅Oracle教程。并在Stack Overflow上搜索许多示例和说明。规范是JSR 310。
您可以直接与数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC驱动程序。无需字符串,无需java.sql.*
类。
如何获取java.time类?
![Table of which java.time library to use with which version of Java or Android.](https://istack.dev59.com/aFsW9.webp)
该
ThreeTen-Extra项目扩展了java.time的附加类。该项目是java.time可能未来添加的试验场。您可能会在此处找到一些有用的类,例如
Interval
,
YearWeek
,
YearQuarter
, 以及
more。
T
对我起作用了(至少在解决解析错误方面是这样的)。 - Agi HammerthiefSimpleDateFormat
和Date
。这些类设计得很差,而且已经过时了,前者尤其令人头疼。相反,应该使用OffsetDateTime
或Instant
。它们都来自于Java时间和日期API的现代化版本。 - Ole V.V.