Search code examples
javadatetimezonesimpledateformatunix-timestamp

Convert time in IDT/IST to unixtime in UTC


I am trying to parse IDT and IST dates to unixtime in UTC
For example:

Thu Sep 10 07:30:20 IDT 2016

For this date I would want to get unix time for the date but in hour of 04:30:20
And if it was IST i would want to get unixtime of 05:30:20 in the same date

SimpleDateFormat formatter= new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
formatter.setTimeZone(TimeZone.getTimeZone("UTC");
System.out.println(formatter.parse(date).getTime())

I still get unixtime of 07:30:20 instead of 05:30:20 or 04:30:20 (IST/IDT)


Solution

  • If you want to see formatted result in UTC then you need a second formatter with possible different pattern and locale and zone set to UTC:

    String input1 = "Sat Sep 10 07:30:20 IDT 2016";
    String input2 = "Sat Dec 10 07:30:20 IST 2016";
    SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
    Date d1 = sdf.parse(input1);
    Date d2 = sdf.parse(input2);
    
    SimpleDateFormat sdfOut =
        new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
    sdfOut.setTimeZone(TimeZone.getTimeZone("UTC"));
    System.out.println("IDT=>UTC: " + sdfOut.format(d1));
    System.out.println("IST=>UTC: " + sdfOut.format(d2));
    

    Output:

    IDT=>UTC: Sat Sep 10 04:30:20 UTC 2016
    IST=>UTC: Sat Dec 10 05:30:20 UTC 2016
    

    The parsing formatter does not need a special zone to be set because your input contains the relevant zone information.

    Side note: Parsing timezone abbreviations like IST is dangerous because this abbreviation has several meanings. You obviously want Israel Time but IST is even more often interpreted as India Standard Time. Well, you are lucky that SimpleDateFormat-symbol "z" interpretes it as Israel Standard Time (works at least for me in my environment). If you want to be sure about the correct interpretation of "IST" then you should consider switching the library and set your preference for Israel Time when parsing, for example in Java-8:

    DateTimeFormatterBuilder.setZoneText(TextStyle.SHORT, Collections.singleton(ZoneId.of("Asia/Jerusalem")))