4

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());
Nital
  • 5,784
  • 26
  • 103
  • 195

2 Answers2

5

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
}
shmosel
  • 49,289
  • 6
  • 73
  • 138
1

Have the class implement Comparable interface, you can use core Java's compareTo method. Works on timestamp in String type, as this is your case.

user3207158
  • 619
  • 2
  • 5
  • 22