0

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)

user3100708
  • 148
  • 3
  • 19

1 Answers1

3

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

Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126
  • Hi. Thanks for the answer. What if I want to get the unixtime of the IDT\IST string date that I got? If I parse the date it return to be local time. any solution for this problem? @Meno Hochschild – user3100708 Jan 20 '17 at 15:22
  • @user3100708 The code above shows how to parse the IDT/IST-string to an object of type `java.util.Date`. This object is never local time (although its method `toString()` describes it incompletely in your system zone with local time). Really, it represents an instant, and its true state can be queried as elapsed time in milliseconds since Unix epoch by [getTime()](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html#getTime--) If using this method then you just need to divide the result by 1000, and you get the Unix time. – Meno Hochschild Jan 20 '17 at 17:42