Java Calendar TimeZone mess

Here is my simple code:

    String defaultSimpleDateFormatPattern = "MMM dd, yyyy HH:mm:ss";
    TimeZone tzNY = TimeZone.getTimeZone("America/New_York");
    TimeZone tzLos = TimeZone.getTimeZone("America/Los_Angeles");
    String dateToTest = "Jan 03, 2015 23:59:59";
    SimpleDateFormat df = new SimpleDateFormat(defaultSimpleDateFormatPattern);
    Calendar c = Calendar.getInstance();
    c.setTime(df.parse(dateToTest)); 
    c.setTimeZone(tzLos);

    System.out.println(c.getTimeZone());
    System.out.println(c.getTime());        
    System.out.println(df.format(c.getTime()));


    Calendar c1 = Calendar.getInstance();
    c1.setTime(df.parse(dateToTest));        
    c1.setTimeZone(tzNY);

    System.out.println(c1.getTimeZone());
    System.out.println(c1.getTime());
    System.out.println(df.format(c1.getTime()));

    System.out.println(c.after(c1)? "after" : (c.before(c1)? "before" : "equal"));

The printout is "equal". How is that? any explanation on this result?

Jon Skeet
people
quotationmark

There are two problems here:

  • You're using an invalid time zone ID (you want America/New_York)
  • You're parsing using a formatter that hasn't got a time zone set (so it'll use the default time zone) and then setting the time zone in the Calendar afterwards... that doesn't change the instant in time being represented

So basically you're parsing to the same Date twice, doing things which don't affect the Date being represented, and then comparing the two equal Date values.

If at all possible, you should use Joda Time or java.time instead of java.util.Calendar, but if you really need to use it, just create two different formatters, one with each time zone. (You'll need to set the time zone in the Calendar as well, if you actually need the Calendar...)

people

See more on this question at Stackoverflow