P. Savrov P. Savrov - 11 months ago 71
Android Question

Difference between two dates (Android)

I need to get a time between two dates. Let's say

dateStart = 1470712122173
dateStop = 1470712127320
The difference between this two dates equals to

So, according to this I expect to get an answer = 5 seconds but I see
. Where these 19 hours come from?

Code for milliseconds ( = 5147) -> time:

private string foo(long dateStart, long dateStop) {
long diff = dateStop - dateStart;
DateFormat simple = SimpleDateFormat.getTimeInstance();
Date date = new Date(diff);
return simple.format(date);

Thank you for explanation.


You need to get the basic concepts right. When you take a difference between two Date object, you get the duration between two points in time, trying to view the difference as another time point makes no sense.

Here's a example using the Java 8 time API to get the difference between two points in time (java.time.Instant):

import java.time.Duration;
import java.time.Instant;

public class TimeDifferenceSample {

    static Duration diff(Instant start, Instant end) {
        return Duration.between(start, end);

    public static void main(String [] args) {
        long start = 1470712122173L;
        long end = 1470712127320L;

        Duration dur = diff(Instant.ofEpochMilli(start), Instant.ofEpochMilli(end));
        System.out.println(dur.getSeconds() + " seconds");


5 seconds

For Android, I am not an expert, but you can check The Joda Time Project, which provides similar functions. I also found an Android verion here.