Android difference between Two Dates Android difference between Two Dates android android

Android difference between Two Dates


DateTimeUtils obj = new DateTimeUtils();SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/M/yyyy hh:mm:ss");try {    Date date1 = simpleDateFormat.parse("10/10/2013 11:30:10");    Date date2 = simpleDateFormat.parse("13/10/2013 20:35:55");    obj.printDifference(date1, date2);} catch (ParseException e) {    e.printStackTrace();}//1 minute = 60 seconds//1 hour = 60 x 60 = 3600//1 day = 3600 x 24 = 86400public void printDifference(Date startDate, Date endDate) {     //milliseconds    long different = endDate.getTime() - startDate.getTime();    System.out.println("startDate : " + startDate);    System.out.println("endDate : "+ endDate);    System.out.println("different : " + different);    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;    System.out.printf(        "%d days, %d hours, %d minutes, %d seconds%n",         elapsedDays, elapsedHours, elapsedMinutes, elapsedSeconds);}

out put is :

startDate : Thu Oct 10 11:30:10 SGT 2013endDate : Sun Oct 13 20:35:55 SGT 2013different : 2919450003 days, 9 hours, 5 minutes, 45 seconds


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


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:

@ExperimentalTimefun 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    }}