[android] Android difference between Two Dates

I have two date like:

String date_1="yyyyMMddHHmmss";
String date_2="yyyyMMddHHmmss";

I want to print the difference like:

2d 3h 45m

How can I do that? Thanks!

This question is related to android date difference

The answer is


When you use Date() to calculate the difference in hours is necessary configure the SimpleDateFormat() in UTC otherwise you get one hour error due to Daylight SavingTime.


DateTime start = new DateTime(2013, 10, 20, 5, 0, 0, Locale);
DateTime end = new DateTime(2013, 10, 21, 13, 0, 0, Locale);
Days.daysBetween(start.toLocalDate(), end.toLocalDate()).getDays()

it returns how many days between given two dates, where DateTime is from joda library


I use this: 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;
}

It will give you difference in months

long milliSeconds1 = calendar1.getTimeInMillis();
long milliSeconds2 = calendar2.getTimeInMillis();
long periodSeconds = (milliSeconds2 - milliSeconds1) / 1000;
long elapsedDays = periodSeconds / 60 / 60 / 24;

System.out.println(String.format("%d months", elapsedDays/30));

Here is the modern answer. It’s good for anyone who either uses Java 8 or later (which doesn’t go for most Android phones yet) or is happy with an external library.

    String date1 = "20170717141000";
    String date2 = "20170719175500";

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
    Duration diff = Duration.between(LocalDateTime.parse(date1, formatter), 
                                     LocalDateTime.parse(date2, formatter));

    if (diff.isZero()) {
        System.out.println("0m");
    } else {
        long days = diff.toDays();
        if (days != 0) {
            System.out.print("" + days + "d ");
            diff = diff.minusDays(days);
        }
        long hours = diff.toHours();
        if (hours != 0) {
            System.out.print("" + hours + "h ");
            diff = diff.minusHours(hours);
        }
        long minutes = diff.toMinutes();
        if (minutes != 0) {
            System.out.print("" + minutes + "m ");
            diff = diff.minusMinutes(minutes);
        }
        long seconds = diff.getSeconds();
        if (seconds != 0) {
            System.out.print("" + seconds + "s ");
        }
        System.out.println();
    }

This prints

2d 3h 45m 

In my own opinion the advantage is not so much that it is shorter (it’s not much), but leaving the calculations to an standard library is less errorprone and gives you clearer code. These are great advantages. The reader is not burdened with recognizing constants like 24, 60 and 1000 and verifying that they are used correctly.

I am using the modern Java date & time API (described in JSR-310 and also known under this name). To use this on Android under API level 26, get the ThreeTenABP, see this question: How to use ThreeTenABP in Android Project. To use it with other Java 6 or 7, get ThreeTen Backport. With Java 8 and later it is built-in.

With Java 9 it will be still a bit easier since the Duration class is extended with methods to give you the days part, hours part, minutes part and seconds part separately so you don’t need the subtractions. See an example in my answer here.


I arranged a little. This works great.

@SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MM yyyy");
    Date date = new Date();
    String dateOfDay = simpleDateFormat.format(date);

    String timeofday = android.text.format.DateFormat.format("HH:mm:ss", new Date().getTime()).toString();

    @SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("dd MM yyyy hh:mm:ss");
    try {
        Date date1 = dateFormat.parse(06 09 2018 + " " + 10:12:56);
        Date date2 = dateFormat.parse(dateOfDay + " " + timeofday);

        printDifference(date1, date2);

    } catch (ParseException e) {
        e.printStackTrace();
    }

@SuppressLint("SetTextI18n")
private void printDifference(Date startDate, Date endDate) {
    //milliseconds
    long different = endDate.getTime() - startDate.getTime();

    long secondsInMilli = 1000;
    long minutesInMilli = secondsInMilli * 60;
    long hoursInMilli = minutesInMilli * 60;
    long daysInMilli = hoursInMilli * 24;

    long elapsedDays = different / daysInMilli;
    different = different % daysInMilli;

    long elapsedHours = different / hoursInMilli;
    different = different % hoursInMilli;

    long elapsedMinutes = different / minutesInMilli;
    different = different % minutesInMilli;

    long elapsedSeconds = different / secondsInMilli;

Toast.makeText(context, elapsedDays + " " + elapsedHours + " " + elapsedMinutes + " " + elapsedSeconds, Toast.LENGTH_SHORT).show();
}

You can calculate the difference in time in miliseconds using this method and get the outputs in seconds, minutes, hours, days, months and years.

You can download class from here: DateTimeDifference GitHub Link

  • Simple to use
long currentTime = System.currentTimeMillis();
long previousTime = (System.currentTimeMillis() - 864000000); //10 days ago

Log.d("DateTime: ", "Difference With Second: " + AppUtility.DateTimeDifference(currentTime, previousTime, AppUtility.TimeDifference.SECOND));
Log.d("DateTime: ", "Difference With Minute: " + AppUtility.DateTimeDifference(currentTime, previousTime, AppUtility.TimeDifference.MINUTE));
  • You can compare the example below
if(AppUtility.DateTimeDifference(currentTime, previousTime, AppUtility.TimeDifference.MINUTE) > 100){
    Log.d("DateTime: ", "There are more than 100 minutes difference between two dates.");
}else{
    Log.d("DateTime: ", "There are no more than 100 minutes difference between two dates.");
}

Short & Sweet:

/**
 * Get a diff between two dates
 *
 * @param oldDate the old date
 * @param newDate the new date
 * @return the diff value, in the days
 */
public static long getDateDiff(SimpleDateFormat format, String oldDate, String newDate) {
    try {
        return TimeUnit.DAYS.convert(format.parse(newDate).getTime() - format.parse(oldDate).getTime(), TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }
}

Usage:

int dateDifference = (int) getDateDiff(new SimpleDateFormat("dd/MM/yyyy"), "29/05/2017", "31/05/2017");
System.out.println("dateDifference: " + dateDifference);

Output:

dateDifference: 2

Kotlin Version:

@ExperimentalTime
fun getDateDiff(format: SimpleDateFormat, oldDate: String, newDate: String): Long {
    return try {
        DurationUnit.DAYS.convert(
            format.parse(newDate).time - format.parse(oldDate).time,
            DurationUnit.MILLISECONDS
        )
    } catch (e: Exception) {
        e.printStackTrace()
        0
    }
}

You can generalize this into a function that lets you choose the output format

private String substractDates(Date date1, Date date2, SimpleDateFormat format) {
    long restDatesinMillis = date1.getTime()-date2.getTime();
    Date restdate = new Date(restDatesinMillis);

    return format.format(restdate);
}

Now is a simple function call like this, difference in hours, minutes and seconds:

SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

try {
    Date date1 = formater.parse(dateEnd);
    Date date2 = formater.parse(dateInit);

    String result = substractDates(date1, date2, new SimpleDateFormat("HH:mm:ss"));

    txtTime.setText(result);
} catch (ParseException e) {
    e.printStackTrace();
}

This works and convert to String as a Bonus ;)

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    try {
        //Dates to compare
        String CurrentDate=  "09/24/2015";
        String FinalDate=  "09/26/2015";

        Date date1;
        Date date2;

        SimpleDateFormat dates = new SimpleDateFormat("MM/dd/yyyy");

        //Setting dates
        date1 = dates.parse(CurrentDate);
        date2 = dates.parse(FinalDate);

        //Comparing dates
        long difference = Math.abs(date1.getTime() - date2.getTime());
        long differenceDates = difference / (24 * 60 * 60 * 1000);

        //Convert long to String
        String dayDifference = Long.toString(differenceDates);

        Log.e("HERE","HERE: " + dayDifference);

    } catch (Exception exception) {
        Log.e("DIDN'T WORK", "exception " + exception);
    }
}

Try this out.

int day = 0;
        int hh = 0;
        int mm = 0;
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy 'at' hh:mm aa");
            Date oldDate = dateFormat.parse(oldTime);
            Date cDate = new Date();
            Long timeDiff = cDate.getTime() - oldDate.getTime();
            day = (int) TimeUnit.MILLISECONDS.toDays(timeDiff);
            hh = (int) (TimeUnit.MILLISECONDS.toHours(timeDiff) - TimeUnit.DAYS.toHours(day));
            mm = (int) (TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff)));



        } catch (ParseException e) {
            e.printStackTrace();
        }

        if (mm <= 60 && hh!= 0) {
            if (hh <= 60 && day != 0) {
                return day + " DAYS AGO";
            } else {
                return hh + " HOUR AGO";
            }
        } else {
            return mm + " MIN AGO";
        }

Date userDob = new SimpleDateFormat("yyyy-MM-dd").parse(dob);
Date today = new Date();
long diff =  today.getTime() - userDob.getTime();
int numOfDays = (int) (diff / (1000 * 60 * 60 * 24));
int hours = (int) (diff / (1000 * 60 * 60));
int minutes = (int) (diff / (1000 * 60));
int seconds = (int) (diff / (1000));

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to difference

Calculate time difference in minutes in SQL Server Java 8: Difference between two LocalDateTime in multiple units Differences between Oracle JDK and OpenJDK Android difference between Two Dates Difference between IsNullOrEmpty and IsNullOrWhiteSpace in C# Get the time difference between two datetimes What is the difference between JVM, JDK, JRE & OpenJDK? What is the difference between bottom-up and top-down? What's the difference between ViewData and ViewBag?