Java TimeUnit Usage getTimeDifference(Date startDate, Date endDate)

Here you can find the source of getTimeDifference(Date startDate, Date endDate)

Description

get Time Difference

License

GNU General Public License

Declaration

public static String getTimeDifference(Date startDate, Date endDate) 

Method Source Code

//package com.java2s;
/*//ww  w. j  a va 2  s . com
 * Title:        EdgeCloudSim - Simulation Utils
 * 
 * Description:  Utility class providing helper functions
 * 
 * Licence:      GPL - http://www.gnu.org/copyleft/gpl.html
 * Copyright (c) 2017, Bogazici University, Istanbul, Turkey
 */

import java.util.Date;

import java.util.concurrent.TimeUnit;

public class Main {
    public static String getTimeDifference(Date startDate, Date endDate) {
        String result = "";
        long duration = endDate.getTime() - startDate.getTime();

        long diffInMilli = TimeUnit.MILLISECONDS.toMillis(duration);
        long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(duration);
        long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);
        long diffInHours = TimeUnit.MILLISECONDS.toHours(duration);
        long diffInDays = TimeUnit.MILLISECONDS.toDays(duration);

        if (diffInDays > 0)
            result += diffInDays + ((diffInDays > 1 == true) ? " Days " : " Day ");
        if (diffInHours > 0)
            result += diffInHours % 24 + ((diffInHours > 1 == true) ? " Hours " : " Hour ");
        if (diffInMinutes > 0)
            result += diffInMinutes % 60 + ((diffInMinutes > 1 == true) ? " Minutes " : " Minute ");
        if (diffInSeconds > 0)
            result += diffInSeconds % 60 + ((diffInSeconds > 1 == true) ? " Seconds" : " Second");
        if (diffInMilli > 0 && result.isEmpty())
            result += diffInMilli + ((diffInMilli > 1 == true) ? " Milli Seconds" : " Milli Second");

        return result;
    }
}

Related

  1. getSeconds(long time)
  2. getSecondsDateDiff(Date dateStart)
  3. getSecondsTimeStamp()
  4. getTime()
  5. getTimeComparisonEpsilonMicros()
  6. getTimeFormat(final long time)
  7. getTimeForS3URL()
  8. getTimeInMillis(String str)
  9. getTimeString(long millis)