0

对于 8601 的日期时间转换,我遵循了这个SO 答案

我将直接从 w3举一个例子:

1994-11-05T08:15:30-05:00 corresponds to November 5, 1994, 8:15:30 am, US Eastern Standard Time.

1994-11-05T13:15:30Z corresponds to the same instant.

这就是我在android中运行的

SimpleDateFormat sdfSource = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ");
dateTime = sdfSource.parse("2014-03-06T11:30:00-05:00");
System.out.println(dateTime); //Thu Mar 06 18:30:00 EET 2014

显然.parse()的输出是本地感知的日期时间。自从我在这个时区以来,已经从EST(-05:00) 转换为(+02:00)。EET但是我不想要这种自动转换。

有没有办法以yyyy-MM-dd'T'HH:mm:ssZZZZZ格式解析日期时间字符串并显示该时区的日期时间?优选输出:

Thu Mar 06 11:30:00 EST 2014

和我的EST位置就是一个例子。它也可以是任何其他时区。

4

3 回答 3

2

内部Date对象是 UTC,这就是它们被解析的内容。

您无法从中检索原始时区,Date但您可以尝试从原始 ISO-8601 戳中检索它,并在格式化时使用它。

当您使用 将其转换为字符串时toString(),它会使用您的本地设置来格式化日期。如果您想要特定的表示,请使用格式化程序来格式化输出,例如

int rawTimeZoneOffsetMillis = ...; // retrieve from ISO-8601 stamp and convert to milliseconds
TimeZone tz = new SimpleTimeZone(rawTimeZoneOffsetMillis, "name");

DateFormat outputFormat = DateFormat.getDateTimeInstance();
outputFormat.setTimeZone(tz);
System.out.println(df.format(dateTime));

ISO-8601 时间戳不能完全用SimpleDateFormat. 这个答案有一些代码可以解决一些限制。

于 2014-03-06T10:32:54.287 回答
0

尽管您在解析日期时不应该担心,因为它被解析为正确的值,可以以您想要的任何格式或时区显示。

SimpleDateFormat sdfSource = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ");
sdfSource.setTimeZone( TimeZone.getTimeZone( "EST" ) );
dateTime = sdfSource.parse("2014-03-06T11:30:00-05:00");
System.out.println(sdfSource.format(dateTime)); //Thu Mar 06 18:30:00 EET 2014
于 2014-03-06T10:16:36.327 回答
0

使用 sdfSource.setTimeZone() 方法

SimpleDateFormat sdfSource = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ");
sdfSource.setTimeZone(TimeZone.getTimeZone("EST")); //give the timezone you want
dateTime = sdfSource.parse("2014-03-06T11:30:00-05:00");
System.out.println(dateTime); //Thu Mar 06 18:30:00 EET 2014

这应该没问题。

于 2014-03-06T10:19:27.847 回答