Java calculate the difference between two datetimes in days, hours, minutes

public class Test {
public void dateDiff(String startTime, String endTime, String format) {
     //Generate a simpledateformate object according to the incoming format
     SimpleDateFormat sd = new SimpleDateFormat(format);
     long nd = 1000*24*60*60;//Number of milliseconds in a day
     long nh = 1000*60*60;//The number of milliseconds in an hour
     long nm = 1000*60;//The number of milliseconds in a minute
     long ns = 1000;//The number of milliseconds in a second
     long diff;
     //Get the millisecond time difference between the two times
     diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
     long day = diff/nd;//Calculate how many days the difference is
     long hour = diff%nd/nh;//Calculate the difference in hours
     long min = diff%nd%nh/nm;//Calculate how many minutes the difference is
     long sec = diff%nd%nh%nm/ns;//Calculate the difference in seconds//Output the result
     System.out.println("Time difference: "+day+"day"+hour+"hour"+min+"minute"+sec+"second.");
    }
}

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327047961&siteId=291194637