javadatetimedatetime-comparison

How to compare the datetime of format "EEE MMM dd HH:mm:ss zzz yyyy" and "yyyy-MM-dd hh:mm:sss" in java?


I have date of type "EEE MM DD HH:mm:ss zzz yyyy" (Wed Mar 04 03:34:45 GMT+08:00 2020) and "yyyy-MM-dd hh:mm:ss" (2020-02-04 02:10:58).How to compare this two date in java?

Both dates are in same timezone.


Solution

  • If you assume that the timezone of the second date is the same as for the first one then you can just use java.time. It has all parsing tools you need. Any other fixed timezone works as well.

    Here is an example:

    String a = "Wed Mar 04 03:34:45 GMT+08:00 2020";
    String b = "2020-02-04 02:10:58";
    
    ZonedDateTime parsedA;
    ZonedDateTime parsedB;
    
    DateTimeFormatter formatterA = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy");
    parsedA = ZonedDateTime.parse(a, formatterA);
    DateTimeFormatter formatterB = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    parsedB = LocalDateTime.parse(b, formatterB).atZone(parsedA.getZone());
    
    // What do you want to compare? For example you can tell if a is after b.
    System.out.println(parsedA.isAfter(parsedB));
    

    Have a look here if you need another format and need a listing of Pattern Letters and Symbols.