How do I get difference between two dates in android?, tried every thing and post

111,665

Solution 1

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

Solution 2

    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);

Solution 3

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();
    }

Solution 4

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

Solution 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.

Share:
111,665
Alex Kapustian
Author by

Alex Kapustian

Updated on February 08, 2022

Comments

  • Alex Kapustian
    Alex Kapustian over 2 years

    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 Kapustian
    Alex Kapustian about 12 years
    Can I create Date object from this info?
  • Dan F
    Dan F about 12 years
    It is a time, not a date, what kind of date are you attempting to create?
  • Basil Bourque
    Basil Bourque over 6 years
    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.
  • neal zedlav
    neal zedlav over 6 years
    Is calendar class an old date-time classes?
  • Basil Bourque
    Basil Bourque over 6 years
    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.
  • Satendra Baghel
    Satendra Baghel over 5 years
    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?
  • Basil Bourque
    Basil Bourque over 5 years
    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.
  • Vyacheslav
    Vyacheslav over 4 years
    I think this is the most appropriate answer. It should be accepted.
  • Deepak Rajput
    Deepak Rajput almost 4 years
    Change diff into : long diff = currentDate.getTime() - oldDate.getTime(); It will help.
  • Johann
    Johann over 2 years
    Requires API Level 31.
  • CoolMind
    CoolMind over 2 years
    Currently we should use inWholeDays instead of inDays.
  • Bartłomiej Uliasz
    Bartłomiej Uliasz over 2 years
    Thank you @CoolMind, I've updated it in my response also
  • CoolMind
    CoolMind over 2 years
    Good job! Probably we don't have to use @ExperimentalTime, I didn't check.
  • Bartłomiej Uliasz
    Bartłomiej Uliasz over 2 years
    Checked and updated with working code.
  • CoolMind
    CoolMind over 2 years
    Well done! Good luck!
  • Ole V.V.
    Ole V.V. over 2 years
    Consider throwing away the long outmoded and notoriously troublesome SimpleDateFormat and friends. See if you either can use desugaring or add 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.