javadatedatetimejava-8date-comparison

Can't convert string to date in Java, wrong timezone after conversion


I have an array of Strings with the dates e.g.:

Now I want to find the most recent date on this list. In order to do that, I try to deserialize these strings to java.util.Date objects and after that compare them.

The code sample of java.util.Date object generation:

strDate = "Tue, 09 Feb 2016 14:07:00 GMT";
DateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");

Date date;
try {

    date = format.parse(strDate);

    //Result: Tue Feb 09 16:07:00 IST 2016
    System.out.println("Result: " + date.toString());

} catch(ParseException e) {
    e.printStackTrace();
}

My questions:

  1. Why is the result in IST 2016 time zone and not in GMT? What does the IST 2016 stand for? Is it India Standard Time or Irish Standard Time or Israel Standard Time?

  2. The initial string is in EEE, dd MMM format, the SimpleDateFormat pattern is also in this format, thus, why the result is in EEE, MMM dd format?

  3. How can get a java.util.Date object in the same timezone as the initial string, in my case — GMT?

  4. Is the approach I'm using to find the most recent date in the list is OK or there is more convenient/modern way to do that in Java 8, e.g., with the usage of LocalDateTime?


Solution

  • You are relying to Date.toString() to print your date when you should format it to a String with a formatter. What you are seeing is just the default pattern of Date.toString(). What you must keep in mind is that a Date does not have a timezone. You are seeing the output with the IST timezone, this must be because the current locale for the JVM is set to some specific locale for which the timezone name is "IST".

    With regard to your point 4, yes, you can do it much cleaner with Java Time API introduced in Java 8. You can create a List of your strings to parse, create a DateTimeFormatter to parse it, and keep the maximum date value.

    public static void main(String[] args) {
    
        List<String> dates = Arrays.asList("Tue, 09 Feb 2016 14:07:00 GMT", "Tue, 09 Feb 2016 19:55:00 GMT");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH);
        
        ZonedDateTime maxDate = dates.stream()
                                     .map(s -> ZonedDateTime.parse(s, formatter))
                                     .max(ZonedDateTime::compareTo)
                                     .get(); // or .orElse(null)
        
        System.out.println(maxDate);
    }
    

    This code is using a ZonedDateTime to keep the time-zone of the incoming strings.