tl;博士
如何将此字符串转换为日期对象
Date 被java.time.Instant 取代。
Instant.parse( "2006-06-21T15:57:24.000Z" )
不改变这种格式
日期时间对象没有“格式”。只有文本有格式。
String output = instant.toString() ; // Generate text in a `String` object in standard ISO 8601 format that represents the value of the `Instant` date-time object.
ISO 8601
输入字符串恰好是标准ISO 8601 格式。末尾的Z 是Zulu 的缩写,意思是UTC。
java.time
在解析和生成表示日期时间值的字符串时,java.time 类默认使用 ISO 8601 格式。
Instant 类表示UTC 中时间轴上的时刻,分辨率为nanoseconds(最多九 (9) 位小数)。
Instant instant = Instant.parse( "2006-06-21T15:57:24.000Z" );
要生成标准 ISO 8601 格式的字符串,请调用 toString。
String output = instant.toString();
2006-06-21T15:57:24Z
字符串 != 日期时间
不要将日期时间对象与表示值的字符串混为一谈。日期时间对象可以解析String,可以生成String,但不是String。换句话说,可以输入和/或输出字符串,但它不是日期时间对象本身。
所以您的问题“如何在不更改此格式的情况下将此字符串转换为日期对象”是没有意义的。
要生成非 ISO 8601 格式的字符串,请将您的 Instant 转换为 OffsetDateTime 或 ZonedDateTime 对象,并使用 DateTimeFormatter 类。在 Stack Overflow 中搜索 DateTimeFormatter 以查看更多讨论和许多示例。
转化
您应该尽可能避免使用旧的 java.util.Date 类。但是,如果您必须与尚未更新为 java.time 类型的旧代码交互,您可以通过添加到旧日期时间类的新方法与 java.time 进行转换。
java.util.Date utilDate = java.util.Date.from( instant );
……然后朝着另一个方向……
Instant instant = utilDate.toInstant();
关于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 类?