在使用具有时区的SimpleDateTimeFormatter时获取不正确的解析日期 [英] Getting incorrect parsed date when using SimpleDateTimeFormatter with time zone

查看:314
本文介绍了在使用具有时区的SimpleDateTimeFormatter时获取不正确的解析日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

  SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
    String s2 = "Mon Oct 19 19:52:21 IST 2015";
    System.out.println(format.parse(s2));

我预计代码将打印Mon Oct 19 07:22:21 PDT 2015,但是令我惊讶的是,它打印了Mon Oct 19 10:52:21 PDT 2015。我可以看到IST是z的有效时区。但是,以下代码工作正常:

I expected that the code would print "Mon Oct 19 07:22:21 PDT 2015", but to my surprise it printed "Mon Oct 19 10:52:21 PDT 2015". I can see that "IST" is a valid time zone for "z". However, the following code worked fine:

SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
    String s2 = "Mon Oct 19 19:52:21 GMT+05:30 2015";
    System.out.println(format.parse(s2));

请帮忙。

推荐答案

使用 IST 是危险的,因为它可以代表印度或以色列ST。
假设您是印度ST,请尝试以下方式:

Using IST is dangerous as it could stand for Indian or Israel ST. Assuming you meant Indian ST, try this:

    SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
    format.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
    String s2 = "Mon Oct 19 19:52:21 IST 2015";
    System.out.println(format.parse(s2));

另外,请遵循@ Meno的回答的建议

Also, follow suggestion from @Meno's answer

这篇关于在使用具有时区的SimpleDateTimeFormatter时获取不正确的解析日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆