80

I saw all the post in here and still I can't figure how do get difference between two android dates.

This is what I do:

long diff = date1.getTime() - date2.getTime();
Date diffDate = new Date(diff);

and I get: the date is Jan. 1, 1970 and the time is always bigger in two hours...I'm from Israel so the two hours is timeOffset.

How can I get normal difference???

Alex K
  • 5,092
  • 15
  • 50
  • 77

15 Answers15

164

You're close to the right answer, you are getting the difference in milliseconds between those two dates, but when you attempt to construct a date out of that difference, it is assuming you want to create a new Date object with that difference value as its epoch time. If you're looking for a time in hours, then you would simply need to do some basic arithmetic on that diff to get the different time parts.

Java:

long diff = date1.getTime() - date2.getTime();
long seconds = diff / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;

Kotlin:

val diff: Long = date1.getTime() - date2.getTime()
val seconds = diff / 1000
val minutes = seconds / 60
val hours = minutes / 60
val days = hours / 24

All of this math will simply do integer arithmetic, so it will truncate any decimal points

Mr. Robot
  • 397
  • 1
  • 14
Dan F
  • 17,654
  • 5
  • 72
  • 110
62
    long diffInMillisec = date1.getTime() - date2.getTime();

    long diffInDays = TimeUnit.MILLISECONDS.toDays(diffInMillisec);
    long diffInHours = TimeUnit.MILLISECONDS.toHours(diffInMillisec);
    long diffInMin = TimeUnit.MILLISECONDS.toMinutes(diffInMillisec);
    long diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMillisec);
Dude
  • 887
  • 6
  • 15
24

Some addition: Here I convert string to date then I compare the current time.

String toyBornTime = "2014-06-18 12:56:50";
    SimpleDateFormat dateFormat = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");

    try {

        Date oldDate = dateFormat.parse(toyBornTime);
        System.out.println(oldDate);

        Date currentDate = new Date();

        long diff = currentDate.getTime() - oldDate.getTime();
        long seconds = diff / 1000;
        long minutes = seconds / 60;
        long hours = minutes / 60;
        long days = hours / 24;

        if (oldDate.before(currentDate)) {

            Log.e("oldDate", "is previous date");
            Log.e("Difference: ", " seconds: " + seconds + " minutes: " + minutes
                    + " hours: " + hours + " days: " + days);

        }

        // Log.e("toyBornTime", "" + toyBornTime);

    } catch (ParseException e) {

        e.printStackTrace();
    }
Shihab Uddin
  • 6,699
  • 2
  • 59
  • 74
  • 1
    From your method i am subtracting two date current date and 10 days old date it is returning negative milliseconds. if using both current day date difference in hour are returning positive milliseconds. Why? – Satendra Baghel Sep 01 '18 at 11:10
  • Change diff into : long diff = currentDate.getTime() - oldDate.getTime(); It will help. – Deepak Rajput Jun 25 '20 at 04:28
15

java.time.Duration

Use java.time.Duration:

    Duration diff = Duration.between(instant2, instant1);
    System.out.println(diff);

This will print something like

PT109H27M21S

This means a period of time of 109 hours 27 minutes 21 seconds. If you want someting more human-readable — I’ll give the Java 9 version first, it’s simplest:

    String formattedDiff = String.format(Locale.ENGLISH,
            "%d days %d hours %d minutes %d seconds",
            diff.toDays(), diff.toHoursPart(), diff.toMinutesPart(), diff.toSecondsPart());
    System.out.println(formattedDiff);

Now we get

4 days 13 hours 27 minutes 21 seconds

The Duration class is part of java.time the modern Java date and time API. This is bundled on newer Android devices. On older devices, get ThreeTenABP and add it to your project, and make sure to import org.threeten.bp.Duration and other date-time classes you may need from the same package.

Assuming you still haven’t got the Java 9 version, you may subtract the larger units in turn to get the smaller ones:

    long days = diff.toDays();
    diff = diff.minusDays(days);
    long hours = diff.toHours();
    diff = diff.minusHours(hours);
    long minutes = diff.toMinutes();
    diff = diff.minusMinutes(minutes);
    long seconds = diff.toSeconds();

Then you can format the four variables as above.

What did you do wrong?

A Date represents a point in time. It was never meant for representing an amount of time, a duration, and it isn’t suited for it. Trying to make that work would at best lead to confusing and hard-to-maintain code. You don’t want that, so please don’t.

Question: Doesn’t java.time require Android API level 26?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
5

What about using Instant:

val instant1 = now()
val instant2 = now()
val diff: Duration = Duration.between(instant1, instant2)
val minutes = diff.toMinutes()

You can even save your Instant using instant1.toString() and parse that string with parse(string).

If you need to support Android API level < 26 just add Java 8+ API desugaring support to your project.

4

If you use Kotlin language for Android development you can get difference in days like this:

fun daysDiff(c1: Calendar, c2: Calendar): Long {
    val diffInMillis = c1.timeInMillis - c2.timeInMillis
    return diffInMillis.milliseconds.inWholeDays
}

or if you want to get results in different type you can replace inWholeDays with toInt(...), toDouble(...), toString(...).

If the only date difference you're interested in is days (let's say as a Double type result) you can create operator extension method like this:

operator fun Calendar.minus(c: Calendar): Double {
    val diffInMillis = timeInMillis - c.timeInMillis
    return diffInMillis.milliseconds.toDouble(DurationUnit.DAYS)
}

And then any operation like calendar2 - calendar1 will return difference in days as Double.

2

Here is my answer based on @Ole V. V. answer.

This also works with Singular.

private String getDuration(Date d1, Date d2) {
    Duration diff = Duration.between(d1.toInstant(), d2.toInstant());


    long days = diff.toDays();
    diff = diff.minusDays(days);
    long hours = diff.toHours();
    diff = diff.minusHours(hours);
    long minutes = diff.toMinutes();
    diff = diff.minusMinutes(minutes);
    long seconds = diff.toMillis();

    StringBuilder formattedDiff = new StringBuilder();
    if(days!=0){
        if(days==1){
            formattedDiff.append(days + " Day ");

        }else {
            formattedDiff.append(days + " Days ");
        }
    }if(hours!=0){
        if(hours==1){
            formattedDiff.append(hours + " hour ");
        }else{
            formattedDiff.append(hours + " hours ");
        }
    }if(minutes!=0){
        if(minutes==1){
            formattedDiff.append(minutes + " minute ");
        }else{
            formattedDiff.append(minutes + " minutes ");
        }
    }if(seconds!=0){
        if(seconds==1){
            formattedDiff.append(seconds + " second ");
        }else{
            formattedDiff.append(seconds + " seconds ");
        }
    }


    return formattedDiff.toString();
}

It works with a StringBuilder to append everything together.

2

I tried this method..but don't know why I am not getting proper result

long diff = date1.getTime() - date2.getTime();
long seconds = diff / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;

But this works

long miliSeconds = date1.getTime() -date2.getTime();
long seconds = TimeUnit.MILLISECONDS.toSeconds(miliSeconds);
long minute = seconds/60;
long hour = minute/60;
long days = hour/24;
sum20156
  • 646
  • 1
  • 7
  • 19
1

Using georgian calander

 public void dateDifferenceExample() {

        // Set the date for both of the calendar instance
        GregorianCalendar calDate = new GregorianCalendar(2012, 10, 02,5,23,43);
        GregorianCalendar cal2 = new GregorianCalendar(2015, 04, 02);

        // Get the represented date in milliseconds
        long millis1 = calDate.getTimeInMillis();
        long millis2 = cal2.getTimeInMillis();

        // Calculate difference in milliseconds
        long diff = millis2 - millis1;

        // Calculate difference in seconds
        long diffSeconds = diff / 1000;

        // Calculate difference in minutes
        long diffMinutes = diff / (60 * 1000);

        // Calculate difference in hours
        long diffHours = diff / (60 * 60 * 1000);

        // Calculate difference in days
        long diffDays = diff / (24 * 60 * 60 * 1000);
    Toast.makeText(getContext(), ""+diffSeconds, Toast.LENGTH_SHORT).show();


}
Syed Danish Haider
  • 1,334
  • 11
  • 15
  • `GregorianCalendar` is a terrible class that was supplanted years ago by the *java.time* classes, specifically `ZonedDateTime`. Suggesting that old class in 2019 is poor advice. For earlier Android, see the *ThreeTen-Backport* and *ThreeTenABP* projects. – Basil Bourque Jan 07 '19 at 08:09
1

when you attempt to construct a date out of that difference, it is assuming you want to create a new Date object with that difference value as its epoch time.

//get time in milliseconds
long diff = date1.getTime() - date2.getTime();
//get time in seconds
long seconds = diff / 1000;
//and so on
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;

for more information you could use these links:

Oracle tutorial: Date Time, explaining how to use java.time.

ThreeTen Backport project, the backport of java.time to Java 6 and 7.

ThreeTenABP, Android edition of ThreeTen Backport.

Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

0

Use these functions

    public static int getDateDifference(
        int previousYear, int previousMonthOfYear, int previousDayOfMonth,
        int nextYear, int nextMonthOfYear, int nextDayOfMonth,
        int differenceToCount){
    // int differenceToCount = can be any of the following
    //  Calendar.MILLISECOND;
    //  Calendar.SECOND;
    //  Calendar.MINUTE;
    //  Calendar.HOUR;
    //  Calendar.DAY_OF_MONTH;
    //  Calendar.MONTH;
    //  Calendar.YEAR;
    //  Calendar.----

    Calendar previousDate = Calendar.getInstance();
    previousDate.set(Calendar.DAY_OF_MONTH, previousDayOfMonth);
    // month is zero indexed so month should be minus 1
    previousDate.set(Calendar.MONTH, previousMonthOfYear);
    previousDate.set(Calendar.YEAR, previousYear);

    Calendar nextDate = Calendar.getInstance();
    nextDate.set(Calendar.DAY_OF_MONTH, previousDayOfMonth);
    // month is zero indexed so month should be minus 1
    nextDate.set(Calendar.MONTH, previousMonthOfYear);
    nextDate.set(Calendar.YEAR, previousYear);

    return getDateDifference(previousDate,nextDate,differenceToCount);
}
public static int getDateDifference(Calendar previousDate,Calendar nextDate,int differenceToCount){
    // int differenceToCount = can be any of the following
    //  Calendar.MILLISECOND;
    //  Calendar.SECOND;
    //  Calendar.MINUTE;
    //  Calendar.HOUR;
    //  Calendar.DAY_OF_MONTH;
    //  Calendar.MONTH;
    //  Calendar.YEAR;
    //  Calendar.----

    //raise an exception if previous is greater than nextdate.
    if(previousDate.compareTo(nextDate)>0){
        throw new RuntimeException("Previous Date is later than Nextdate");
    }

    int difference=0;
    while(previousDate.compareTo(nextDate)<=0){
        difference++;
        previousDate.add(differenceToCount,1);
    }
    return difference;
}
  • 1
    This code uses troublesome old date-time classes now supplanted by the java.time classes. For older Java and Android, see the *ThreeTen-Backport* and *ThreeTenABP* projects. – Basil Bourque Nov 29 '17 at 09:26
  • Is calendar class an old date-time classes? – neal zedlav Dec 05 '17 at 03:42
  • 1
    Yes, any date-time related class found outside the `java.time` package is now legacy and should be avoided. This includes `Date` and `Calendar`, and the java.sql classes. See the Oracle Tutorial. – Basil Bourque Dec 05 '17 at 05:02
0

written in Kotlin: if you need difference between 2 dates and don't care about the dates itself ( good if you need to do something in the app,based on time from other operation time that was saved in shared preferences for example). save first time :

val firstTime:Long= System.currentTimeMillis()

save second time:

val now:Long= System.currentTimeMillis()

calculate the miliseconds between 2 times:

val milisecondsSinceLastTime: Long =(now-lastScrollTime)
Gilad Levinson
  • 234
  • 2
  • 12
0

Get time difference between AM and PM

private int  getTimeDiff() {
    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss aa");
    Date systemDate = Calendar.getInstance().getTime();
    String myDate = sdf.format(systemDate);
    Date current = null;
    Date Date2 = null;
    try {
        current = sdf.parse(myDate);
        // current = sdf.parse("05:00:00 pm");
        Date2 = sdf.parse("12:00:00 am");
    } catch (ParseException e) {
        e.printStackTrace();
    }
    long millse = Date2.getTime() - current.getTime();
    long mills = Math.abs(millse);
    int Hours = (int) (mills / (1000 * 60 * 60));
    int Mins = (int) (mills / (1000 * 60)) % 60;
    long Secs = (int) (mills / 1000) % 60;
    String diff = Hours + ":" + Mins + ":" + Secs;
    int min = 60-Mins;
    if (Hours >= 12) {
        String requiredTime = 24 - Hours + ":" + Mins + ":" + Secs;
        int minutes= ((24-Hours)*60)-Mins;
        return minutes;

    } else {
        int time = 12 - Hours;
        int hours=time+12;
        int res = (hours*60);
        int minutes = res-Mins;
        return minutes;
    }
}
Ubaid
  • 1
  • 1
  • Consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends. See if you either can use [desugaring](https://developer.android.com/studio/write/java8-support-table) or add [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project, in order to use java.time, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Feb 06 '22 at 15:45
0

The other answers are Ok in some cases they work perfect but when there is time difference between two dates( Like I am comparing two dates with different time then the difference between two dates either will be less than 24 hours which I can't afford or greater than 24 hours ) then it will not work so here is my approach

    fun isSameDay(date1: Date, date2: Date): Boolean {
       val format = SimpleDateFormat("dd/MM/yyyy")
       return format.format(date1).equals(format.format(date2))
    }
  • 2
    Thanks for wanting to contribute. Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. We have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. Yes, you can use it on Android. For older Android look into [desugaring](https://developer.android.com/studio/write/java8-support-table). – Ole V.V. Jan 05 '23 at 20:04
-1

shortest answer that works for me. send start and end date in millisecond.

public int GetDifference(long start,long end){
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(start);
    int hour = cal.get(Calendar.HOUR_OF_DAY);
    int min = cal.get(Calendar.MINUTE);
    long t=(23-hour)*3600000+(59-min)*60000;

    t=start+t;

    int diff=0;
    if(end>t){
        diff=(int)((end-t)/ TimeUnit.DAYS.toMillis(1))+1;
    }

    return  diff;
}
ahmad dehghan
  • 37
  • 1
  • 3