0

I have time in this format: If I have times like Y1 = 05:41:54.771 and Y2 = 05:42:03.465, I want to have exact difference in milliseconds. For the above example the exact millisecond difference would be "6693 milliseconds". How do I achieve this?


            Date date = new Date(timestamp);
  DateFormat format = new SimpleDateFormat("hh:mm:ss.SSS",Locale.getDefault());
       
    
} 
    



3 Answers3

2

The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.

Using the modern date-time API:

import java.time.Duration;
import java.time.LocalTime;

public class Main {
    public static void main(String[] args) {
        long millisBetween = Duration.between(LocalTime.parse("05:41:54.771"), LocalTime.parse("05:42:03.465"))
                                .toMillis();
        System.out.println(millisBetween);
    }
}

Output:

8694

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

Using the legacy API:

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;

public class Main {
    public static void main(String[] args) throws ParseException {
        DateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS", Locale.ENGLISH);
        long millisBetween = sdf.parse("05:42:03.465").getTime() - sdf.parse("05:41:54.771").getTime();
        System.out.println(millisBetween);
    }
}

Output:

8694

Some important notes about this solution:

  1. Without a date, SimpleDateFormat parses the time string with a date of January 1, 1970 GMT.
  2. Date#getTime returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
  3. Use H instead of h for a time value in 24-Hour format.
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
1

You are in the right direction. Using the DateFormat's parse() method you can get a Date object. Then convert it to instant and get the millis since epoch. Finally it's a simple subtraction.

DateFormat format = new SimpleDateFormat("hh:mm:ss.SSS", Locale.getDefault());

try {
    Instant y1 = format.parse("05:41:54.771").toInstant();
    Instant y2 = format.parse("05:42:03.465").toInstant();

    long diffMillis = y2.toEpochMilli() - y1.toEpochMilli();
    System.out.println(diffMillis);

} catch (ParseException e) {
    throw new RuntimeException(e);
}
Minas Mina
  • 2,058
  • 3
  • 21
  • 35
  • Well thanks for the idea. I tried your code but I got some other issue . I using above code (did changes recent) for my work to be done .Could u help me with that by what improvement I could achieve the same. – Satyam Raikwar Jan 04 '21 at 11:23
  • 1
    You’re converting from string to `Date`, then to `Instant` to `long` and finally subtracting “by hand”. This solution is *a lot* more complicated than needed. (1) Skip the poorly designed and long outdated `Date` and `SimpleDateFormat` classes. (2) For a time of day use `LocalTime` (not `Instant`). (3) Let Java find the difference in millis for you, for example using `ChronoUnit.MILLIS.between()`. See in the good answer by Live and Let Live how simple it is. – Ole V.V. Jan 07 '21 at 22:21
0

The line of code you have provided is a DateFormat object that takes a date and formats it into a string representation. It doesn't have any actual data stored in it. You want to make a comparison on the actual date object, not the formatter.

There are a few different ways to store time, but a common way to store timestamps is as a Long. Since longs are numbers, you can do comparison and math just like an Int:

Long startTime = System.currentTimeMillis();
// Do some long task here that we want to know the duration of
Long endTime = System.currentTimeMillis();

Long difference = endTime - startTime;

Alternatively, there are libraries and tools for dealing with structured time data that may have other ways of storing timestamps and comparing them, however this is a quick example of a common simple implementation if you just need to quickly compare two timestamps.

RedBassett
  • 3,469
  • 3
  • 32
  • 56
  • The question asks for the difference in millis between two timestamps, not to calculate elapsed time. And even if it did, this solution is flawed, because it is prone to time changes (if the time changes between the two calls, you'd get a wrong answer). The correct way would be to use `System.nanoTime()`, calculate the difference and convert it to milliseconds. – Minas Mina Jan 01 '21 at 22:30
  • I use elapsed time as an example, the source of the two timestamps doesn't matter. As noted in the answer, this is a very simple implementation using common patterns that works in most cases on a standard system implementation. My main point to the original question is that `DateFormat` doesn't have anything to do with the calculation asked for and that calculating the difference between two time stamps depends on how they are stored. – RedBassett Jan 01 '21 at 22:57