Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to compare two different timestamp and find the latest

I have the two different timestamp values as String. I need to find which one is latest. Its in the format of [YYYYMMDDHHMMSS]

Timestamps are :

20150804030251
20150804040544

Is there any easy way to get the latest using Java 8?

like image 554
Shankar Avatar asked Nov 15 '25 09:11

Shankar


1 Answers

Yes, those timestamps are formated in a way which is easy to compare.

if ( Long.parseLong(timesteamp1) < Long.parseLong(timestamp2) ) {
  //timestamp2 is later than timestamp1
}

This is possible because the most significative part, the year, is in the most significative part of an integer, the leftmost; the rest of the parts go in decreasing order of significance from left to right; and a fixed number of digits is used for each part, like month 02 instead of month 2. Otherwise this simple way would not be possible.

You can also compare them lexicografically. The previous code, in the particular case of this format, is equivalent to :

if ( timestamp1.compareTo(timestamp2) < 0 ) {
  // timestamp2 is later than timestamp 1
}
like image 176
Anonymous Coward Avatar answered Nov 18 '25 05:11

Anonymous Coward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!