Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java timezone - strange behavior with IST?

Tags:

java

timezone

I have the below code:

DateFormat df = new SimpleDateFormat("M/d/yy h:mm a z");
df.setLenient(false);
System.out.println(df.parse("6/29/2012 5:15 PM IST"));

Assuming I now set my PC's timezone to Pacific Time (UTC-7 for PDT), this prints

Fri Jun 29 08:15:00 PDT 2012

Isn't PDT 12.5 hours behind IST (Indian Standard Time)? This problem does not occur for any other timezone - I tried UTC, PKT, MMT etc instead of IST in the date string. Are there two ISTs in Java by any chance?

P.S: The date string in the actual code comes from an external source, so I cannot use GMT offset or any other timezone format.

like image 374
Vasan Avatar asked Nov 16 '25 20:11

Vasan


2 Answers

The abberviated names of timezone are ambiguous and have been deprecated for Olson names for timezones. The following works consistently as there may be be differences in the way parse() and getTimezone() behaves.

SimpleDateFormat sdf = new SimpleDateFormat("M/d/yy h:mm a Z");
TimeZone istTimeZone = TimeZone.getTimeZone("Asia/Kolkata");
Date d = new Date();
sdf.setTimeZone(istTimeZone);
String strtime = sdf.format(d);
like image 196
rnk Avatar answered Nov 19 '25 09:11

rnk


Sorry, I have to write an answer for this, but try this code:

public class Test {

    public static void main(String[] args) throws ParseException {
        DF df = new DF("M/d/yy h:mm a z");
        String [][] zs = df.getDateFormatSymbols().getZoneStrings();
        for( String [] z : zs ) {
            System.out.println( Arrays.toString( z ) );
        }
    }

    private static class DF extends SimpleDateFormat {
        @Override
        public DateFormatSymbols getDateFormatSymbols() {
            return super.getDateFormatSymbols();
        }

        public DF(String pattern) {
            super(pattern);
        }
    }

}

You'll find that IST appears several times in the list and the first one is indeed Israel Standard Time.

like image 26
biziclop Avatar answered Nov 19 '25 08:11

biziclop