SimpleDateFormat ignores TimeZone

[亡魂溺海] 提交于 2019-12-12 02:22:25

问题


I have read a bunch of posts on this, but, I am obviously missing something. I have date string, and a time zone. I am trying to instantiate a date object as follows:

        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC")); 
        java.util.Date dateObj = sdf.parse("2013-10-06 13:30:00");
        System.out.println(dateObj);

What is printed is: Sun Oct 06 09:30:00 EDT 2013

What I want is a date object in UTC format. Not one converted to EDT. What am I doing wrong?

Thanks.


回答1:


This is because a Date object does not store any timezone information. Date basically only stores the number of milliseconds since the epoch (Jan. 1, 1970). By default Date will use the timezone associated with the JVM. In order to preserve timezone information you should continue using the DateFormat object that you've already got.

See DateFormat#format(Date): http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html#format(java.util.Date)

The following should give you what you're looking for:

System.out.println(sdf.format(dateObj));



回答2:


Try below code, you'll see that the date parsed 1st time is different from the one parsed after setting timezone. Actually the date is parsed as expected in right timezone. It s while printing it gives you get the machines's default TZ. You could have printed the dateObj.toGMTString() to check the same, but that is deprecated.

    final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    Date dateObj = sdf.parse("2013-10-06 13:30:00");
    System.out.println(dateObj.toString());

    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    dateObj = sdf.parse("2013-10-06 13:30:00");
    System.out.println(dateObj.toString());


来源:https://stackoverflow.com/questions/30271681/simpledateformat-ignores-timezone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!