Java 如何使用 Joda Time 解析包含时区的日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1327229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I parse a date including timezone with Joda Time
提问by Steve McLeod
This snippet of code always parses the date into the current timezone, and not into the timezone in the string being parsed.
这段代码总是将日期解析为当前时区,而不是解析字符串中的时区。
final DateTimeFormatter df = DateTimeFormat
.forPattern("EEE MMM dd HH:mm:ss 'GMT'Z yyyy");
final DateTime dateTime = df
.parseDateTime("Mon Aug 24 12:36:46 GMT+1000 2009");
System.out.println("dateTime = " + dateTime);
// outputs dateTime = 2009-08-24T04:36:46.000+02:00
It outputs:
它输出:
dateTime = 2009-08-24T04:36:46.000+02:00
whereas I expect:
而我期望:
dateTime = 2009-08-24T04:36:46.000+10:00
Any ideas what I'm doing wrong?
任何想法我做错了什么?
采纳答案by Steve McLeod
OK, further Googling gave me the answer to my own question: use withOffsetParsed()
, as so:
好的,进一步的谷歌搜索给了我自己问题的答案:使用withOffsetParsed()
,如下所示:
final DateTimeFormatter df = DateTimeFormat
.forPattern("EEE MMM dd HH:mm:ss 'GMT'Z yyyy");
final DateTime dateTime = df.withOffsetParsed()
.parseDateTime("Mon Aug 24 12:36:46 GMT+1000 2009");
This works.
这有效。
回答by z0mb1ek
also you can chose:
你也可以选择:
// parse using the Paris zone
DateTime date = formatter.withZone(DateTimeZone.forID("Europe/Paris")).parseDateTime(str);