现代方法是使用 java.time 类。
ZonedDateTime
指定格式模式以匹配您的输入字符串。代码类似于SimpleDateFormat,但不完全一样。请务必阅读DateTimeFormatter 的课程文档。请注意,我们指定 Locale 来确定使用什么人类语言来表示星期几和月份的名称。
String input = "Wed Jul 08 17:08:48 GMT 2009";
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "EEE MMM dd HH:mm:ss z uuuu" , Locale.ENGLISH );
ZonedDateTime zdt = ZonedDateTime.parse ( input , f );
zdt.toString(): 2009-07-08T17:08:48Z[GMT]
我们可以将其调整到任何其他时区。
以continent/region 的格式指定proper time zone name。切勿使用 3-4 个字母的缩写,例如 CDT 或 EST 或 IST,因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。
我猜CDT 是指像America/Chicago 这样的时区。
ZoneId z = ZoneId.of( "America/Chicago" );
ZonedDateTime zdtChicago = zdt.withZoneSameInstant( z );
zdtChicago.toString() 2009-07-08T12:08:48-05:00[美国/芝加哥]
Instant
通常最好在 UTC 工作。为此提取Instant。 Instant 类代表UTC 中时间线上的时刻,分辨率为nanoseconds(最多九 (9) 位小数)。
Instant 类是 java.time 的基本构建块类。您可以将ZonedDateTime 视为Instant 加上ZoneId。
Instant instant = zdtChicago.toInstant();
instant.toString(): 2009-07-08T17:08:48Z
关于java.time
java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.Date、.Calendar 和 java.text.SimpleDateFormat。
Joda-Time 项目现在位于maintenance mode,建议迁移到 java.time。
要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310。
从哪里获得 java.time 类?
ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是未来可能添加到 java.time 的试验场。您可以在这里找到一些有用的类,例如Interval、YearWeek、YearQuarter 和more。