How to subtract dates using java.sql.Timestamp

Uday Kiran :

I am practically checking how much time taking by collection(s) insertion with 'N' elements,

Now I am stuck in checking total time taken by ArrayList in Insertion process.

Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis());
    System.out.println("Start Insertion :: "+startTimeStamp);

    List<Integer> intList = new ArrayList<>();
    for (int i = 0; i <= 100000000; i++) {
        intList.add(i);
    }
    Timestamp endTimeStamp = new Timestamp(System.currentTimeMillis());
    System.out.println("End insertion :: "+endTimeStamp);
    // Total time taken 
    // TODO       

Output : Start Insertion :: 2020-03-19 16:47:27.395 End insertion :: 2020-03-19 16:48:11.963

John Bollinger :

The simple, old-school way would be to use the getTime() method on each Timestamp and subtract the results, giving you the number of milliseconds elapsed between the two:

long millisElapsed = endTimeStamp.getTime() - startTimeStamp.getTime();

Using more modern APIs, though, you would probably convert each timestamp to an Instant, and compute the Duration bracketed by those:

Duration elapsedDuration =
        Duration.between(startTimeStamp.toInstant(), endTimeStamp.toInstant());

A Duration has considerably more structure and support than a primitive long, but perhaps it's more than you need.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=316874&siteId=1