Doo Dah
Doo Dah

Reputation: 4029

SimpleDateFormat ignores TimeZone

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.

Upvotes: 0

Views: 1251

Answers (2)

Nitin Dandriyal
Nitin Dandriyal

Reputation: 1607

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());

Upvotes: 1

adchilds
adchilds

Reputation: 963

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));

Upvotes: 3

Related Questions