4

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?

Shankar
  • 8,529
  • 26
  • 90
  • 159

5 Answers5

4

You don't even have to parse those strings. Just use compareTo():

"20150804030251".compareTo("20150804040544");

More info

Erwan C.
  • 709
  • 5
  • 18
3

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
}
Anonymous Coward
  • 3,140
  • 22
  • 39
3

you can create local date object In java 8, like below

LocalDateTime dt = LocalDateTime.parse("20150804030251",
                DateTimeFormatter.ofPattern("YYYYMMDDHHMMSS")

LocalDateTime dt2 = LocalDateTime.parse("20150804030251",
                DateTimeFormatter.ofPattern("YYYYMMDDHHMMSS")

then compare using dt.isBefore(dt2)

Nitesh Virani
  • 1,688
  • 4
  • 25
  • 41
  • 1
    I have already tried this one, but it wasn't working. i got parsing exception. – Shankar Aug 06 '15 at 08:28
  • The basic idea is the right one. I too get `java.time.format.DateTimeParseException: Text '20150804030251' could not be parsed at index 0`, though (after completing the statements). You need to beware of the case of format pattern letters. – Ole V.V. May 09 '21 at 06:56
1

You can still try this. In here not use any special feature in Java 8

String timeStamp1 = "20150804030251";
String timeStamp2 = "20150804040544";
DateFormat dateFormat = new SimpleDateFormat("yyyyMMhhHHmmss");
Date date1 = dateFormat.parse(timeStamp1);
Date date2 = dateFormat.parse(timeStamp2);
if(date1.after(date2)){
  System.out.println("latest "+date1);
}else {
  System.out.println("latest "+date2);
}
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
  • You misunderstood what those numbers are. The first, for example, should signify August 4, 2015, 03:02:51. Instead your code gives Thu Jul 21 23:33:50 CEST 2608 (almost 600 years off). – Ole V.V. May 09 '21 at 07:32
1

Unfortunately, none of the existing answers is proper. Let's first discuss the problem with them:

  • The accepted answer works as a result of mere coincidence. It happened to work just because the values are arranged in the decreasing order of time units (year, month, day, hour, minute, second). It will fail if their positions are changed e.g. MMyyyy.... Another serious problem with this approach is that it will fail to validate a wrong value e.g. 15 digits instead of 14 digits.
  • This has similar problems as with the accepted answer. Instead of numeric value, it compares ASCII values and thus may fail for the same reasons as mentioned for the accepted answer.
  • This is the idiomatic way of doing it, but it is wrong because it uses Y (which specifies week-based-year) instead of y (which specifies year-of-era) and D (which specifies day-of-year) instead of d (which specifies day-of-month). In fact, it is recommended to use u instead of y. Check the documentation page to learn more about these symbols.
  • This is blatantly wrong. Date(long date) should initialize the object with the no. of milliseconds since 1970-01-01T00:00:00Z.

By now, you must have already figured out the solution which I have posted below just for the sake of completeness:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        String strDateTime1 = "20150804030251";
        String strDateTime2 = "20150804040544";

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuuMMddHHmmss");

        LocalDateTime ldt1 = LocalDateTime.parse(strDateTime1, dtf);
        LocalDateTime ldt2 = LocalDateTime.parse(strDateTime2, dtf);

        LocalDateTime latest = ldt1.isAfter(ldt2) ? ldt1 : ldt2;

        System.out.println(latest);
    }
}

Output:

2015-08-04T04:05:44

Learn more about the the modern date-time API* from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • 1
    A very, very good answer. Setting everything straight and giving the exact best solution to the question. – Ole V.V. May 09 '21 at 07:35
  • The question says "Its in the format of [YYYYMMDDHHMMSS]" so it doesn't work "as a result of mere coincidence." The answer is good for a more general case. But a big part of coding is to understand what you are doing. And KISS ;) – Erwan C. Oct 06 '21 at 16:34