Snippets

Muhammed Ballan Difference between 2 dates in hours minutes seconds Example

Created by Muhammed Ballan last modified
// As simple as that
public static String diffBetween(Date start, Date end) {
    long diffInMilliSeconds = end.getTime() - start.getTime();

    int hours = (int) ((diffInMilliSeconds / 1000) / 3600);
    int minutes = (int) (((diffInMilliSeconds / 1000) / 60) % 60);
    int seconds = (int) ((diffInMilliSeconds / 1000) % 60);
    return String.format("%02d:%02d:%02d", hours , minutes, seconds );
}

public static String checkNowIfBetween(Date start, Date end) {
    Date now = Calendar.getInstance().getTime();
    //        if ( start.compareTo(now) * now.compareTo(end) > 0 )
    //        if ( !now.before(start) && !now.after(end)) // include end points
    if ( now.after(start) && now.before(end)) // exclude end points
        return "YES";
    else
        return "NO";
}

// EXAMPLE
Calendar calendar = Calendar.getInstance();
// Date now = new Date(System.currentTimeMillis());
Date now = calendar.getTime();
calendar.setTime(now);
calendar.add(Calendar.DATE, 1);
calendar.add(Calendar.MINUTE, 10);
calendar.add(Calendar.SECOND, 65);

Log.d(TAG, diffBetween(now, calendar.getTime()));

// Result 24:11:05

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.