tl;博士
OffsetDateTime.parse( // Parse input string as a `OffsetDateTime` object, with the given offset-from-UTC.
"Sat Mar 01 15:52:20 GMT+1:00 2014" ,
DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss O uuuu" , Locale.US )
).toInstant() // Convert from the given offset-from-UTC to UTC.
详情
您可能对 Java 中日期和时间跟踪的工作方式感到困惑。 java.util.Date 类跟踪自Unix epoch 以来的毫秒数。它里面没有字符串。
java.time
现代方法使用 java.time 类。
如果您收到"Sat Mar 01 15:52:20 GMT+1:00 2014" 之类的字符串,请解析为OffsetDateTime。顺便说一句,这是一个可怕格式。尽可能使用标准 ISO 8601 格式将日期时间值作为文本交换。
指定格式模式以匹配您的输入。
注意Locale 参数。 Locale 确定 (a) 用于翻译日期名称、月份名称等的人类语言,以及 (b) 决定缩写、大写、标点符号、分隔符等问题的文化规范。
String input = "Sat Mar 01 15:52:20 GMT+1:00 2014" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss O uuuu" , Locale.US );
OffsetDateTime odt = OffsetDateTime.parse( input , f );
生成一个字符串,以标准ISO 8601 格式表示此OffsetDateTime 对象的值。
odt.toString(): 2014-03-01T15:52:20+01:00
要生成其他格式的字符串,请在 Stack Overflow 中搜索 DateTimeFormatter。
要通过 UTC 的挂钟时间查看同一时刻,请提取 Instant 对象。
Instant instant = odt.toInstant() ; // Extract an `Instant`, always in UTC.
乔达时间
更新:此部分现已过时,但保留为历史。仅供参考,Joda-Time 项目现在位于maintenance mode,团队建议迁移到java.time 类。
Joda-Time 是数据时间处理的首选库。与 Java 捆绑在一起的 java.util.Date 和 .Calendar 和 SimpleTextFormat 类是出了名的麻烦(不是 Sun 最好的工作)。 Java 8 中的那些旧课程已被受 Joda-Time 启发的新 java.time package 所取代。
在 Joda-Time 中,DateTime 对象类似于 java.util.Date 对象,因为它跟踪自 Unix 纪元以来的毫秒数。但不同之处在于 DateTime 确实知道自己分配的时区。
这里有一些代码可以帮助您入门。搜索 StackOverflow 以查找更多示例。
您作为示例给出的字符串存在一个问题。与 GMT 的偏移量是 +1:00,在 1 之前没有前导零。 Joda-Time 无法直接解析。希望这是您的错字,而不是 Parse.com 生成的糟糕格式。
您在下面看到的格式是标准格式,ISO 8601。
String input = "Sat Mar 01 15:52:20 GMT+01:00 2014";
DateTimeFormatter formatterInput = DateTimeFormat.forPattern( "EEE MMM dd HH:mm:ss 'GMT'Z yyyy" ).withLocale( Locale.ENGLISH );
DateTimeZone timeZone = DateTimeZone.forID( "America/Los_Angeles" );
DateTime dateTimeLosAngeles = formatterInput.withZone( timeZone ).parseDateTime( input );
DateTime dateTimeUtc = dateTimeLosAngeles.withZone( DateTimeZone.UTC );
DateTimeFormatter formatterOutput = DateTimeFormat.forStyle( "SS" );
String output = formatterOutput.print( dateTimeLosAngeles );
转储到控制台...
System.out.println( "input: " + input );
System.out.println( "dateTimeLosAngeles: " + dateTimeLosAngeles );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "output: " + output );
运行时……
input: Sat Mar 01 15:52:20 GMT+01:00 2014
dateTimeLosAngeles: 2014-03-01T06:52:20.000-08:00
dateTimeUtc: 2014-03-01T14:52:20.000Z
output: 3/1/14 6:52 AM
关于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 类?