Java to get the time of two times, such as 1 day, 2 hours and 30 minutes

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtil {
public static void main(String[] args) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date1 = format.parse("2012-10-11 07:18:54");
Date date2 = format.parse("2012-12-11 09:18:44");
String diff = diffDate(date1.getTime(), date2.getTime());
System.out.println(diff);
}
/**
*
获取两个时间的时间查 如
1

2
小时
30
分钟
*/
public static String diffDate(long from, long to) {
String diff = "";
long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60;
long nm = 1000 * 60;
// long ns = 1000;
//
get the millisecond time difference between two times
long _diff = to - from;
if (_diff <= 0) {
diff = "0d";
return diff;
}
//
calculate the difference in days
long day = _diff / nd;
//
calculate the difference in hours
long hour = _diff % nd / nh;
//
Calculate the difference in minutes
long min = _diff % nd % nh / nm;
//
Calculate the difference in seconds
//
output the result
// long sec = diff % nd % nh % nm / ns;
if (day > 0 ) {
diff += day + "d ";
}
if (hour > 0) {
diff += hour + "h ";
}
if (min > 0) {
diff += min + "m";
}
return diff;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326249205&siteId=291194637