strange behavior with IST?

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?

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


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.


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

Not an answer but see the output + code below - it does seem that parse treats IST differently from TimeZone.getTimeZone("IST") ...

Fri Jun 29 16:15:00 BST 2012
Fri Jun 29 12:45:00 BST 2012
Fri Jun 29 12:45:00 BST 2012
*BST = London

public static void main(String[] args) throws InterruptedException, ParseException {
    DateFormat fmt1 = new SimpleDateFormat("M/d/yy h:mm a Z");
    Date date = fmt1.parse("6/29/2012 5:15 PM IST");
    System.out.println(date);

    DateFormat fmt2 = new SimpleDateFormat("M/d/yy h:mm a");
    fmt2.setTimeZone(TimeZone.getTimeZone("IST"));
    System.out.println(fmt2.parse("6/29/2012 5:15 PM"));

    DateFormat fmt3 = new SimpleDateFormat("M/d/yy h:mm a");
    fmt3.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
    System.out.println(fmt3.parse("6/29/2012 5:15 PM"));
}
链接地址: http://www.djcxy.com/p/3066.html

上一篇: Java以这种格式减去两个日期

下一篇: 与IST的奇怪行为?