3

I am trying to parse a string of format

Thu Apr 07 11:45:28 AEST 2016

into date object. My code looks like following:

SimpleDateFormat parserSDF = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
try{
    Date time = parserSDF.parse("Sat Feb 01 15:00:19 AEDT 2014");
}catch(Exception e){
    e.printStackTrace();
}

But I am getting a 'parse error'. I cannot change the input format of the date and I also cannot set my timezone to a static value as this code is to be run on andorid device. How can I parse this string into date ?

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
Rahul
  • 322
  • 1
  • 5
  • 18

1 Answers1

2

Using the java.time framework (JSR 310), you can do:

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE MMM d HH:mm:ss zzz yyyy");
ZonedDateTime zdt = ZonedDateTime.parse("Sat Feb 01 15:00:19 AEDT 2014", dtf);
System.out.println(zdt);

…which prints:

2014-02-01T15:00:19+11:00[Australia/Sydney]

Though why it picks Sydney instead of Melbourne I am not sure.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 1
    It looks like it picked the last one in this list sorted by timezone name alphabetically: Australia/Currie, Australia/Hobart, Australia/Melbourne, Australia/Sydney. Each of these timezones are consistent with the input, and with each other on this particular date. I'm curious what it would do if you gave it date/time/abbreviation that matched two or more timezones that are *not* consistent with each other. – Howard Hinnant Apr 07 '16 at 12:14
  • 1
    For example "Thu Apr 07 11:45:28 BST 2016". This matches Europe/London 2016-04-07 10:45:28 UTC and Pacific/Bougainville 2016-04-07 00:45:28 UTC. – Howard Hinnant Apr 07 '16 at 12:25
  • 1
    @HowardHinnant “I'm curious … if it … matched two or more timezones that are not consistent…” That is why you should **avoid using those 3-4 letter zone abbreviations** in the first place. They are not real time zones, not standardized, and not unique (ex: `IST` is India time and Irish time, etc.). Use [proper time zone names](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) in the format of `continent/region`. And for the sake of both your success and sanity, avoid those old date-time classes (java.util.Date/.Calendar etc.). Use java.time classes as shown here by Lawrey. – Basil Bourque Apr 10 '16 at 02:54
  • 1
    @BasilBourque: Thanks, I'm relatively familiar with all that. My curiosity was about how the software responded to such a request. I credit this question/answer with helping me design how *my* C++ timezone library will respond: http://howardhinnant.github.io/tz.html#Parsing – Howard Hinnant Apr 10 '16 at 14:44
  • 1
    Hehe: "Australia/Currie". I assume that was an auto-corrected "Australia/Canberra" (which is where I live), but Australia/Currie, I like it ;) – Slartibartfast Jul 06 '18 at 07:16