Search code examples
javatimestamputc

How to compare two utc timestamps in Java?


I am using the below method to generate a UTC timestamp and would like to compare it with another. I am using Apache Commons Lang library for this.

How can I compare the two timestamps and determine which one is bigger?

String msgPushedTimestamp = 2016-05-11T19:50:17.141Z
String logFileTimestamp = 2016-05-11T14:52:02.970Z

This is how I am generating the timestamp using Apache Commons Lang library.

String msgPushedTimestamp = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", TimeZone.getTimeZone("UTC")).format(System.currentTimeMillis());

Solution

  • You can compare them as strings because your date format (ISO 8601) is lexicographically comparable.

    int compare = msgPushedTimestamp.compareTo(logFileTimestamp);
    if (compare < 0) {
        // msgPushedTimestamp is earlier
    } else if (compare > 0) {
        // logFileTimestamp is earlier
    } else {
        // they are equal
    }