大马资讯论坛 - 马来西亚中文资讯平台
标题:
[教学] Java 计算时间差,处理秒、分钟、小时、天、月、年
[打印本页]
作者:
资讯王
时间:
2014-2-24 00:33
标题:
[教学] Java 计算时间差,处理秒、分钟、小时、天、月、年
Java 处理日期格式为秒前、分钟前、小时前、天前、月前、年前 - Time Elapsed In Years, Months, Days, Hours, Minutes, Seconds
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("dd/M/yyyy hh:mm:ss");
Date date1 = simpleDateFormat.parse("13/10/2013 11:30:10");
Date date2 = simpleDateFormat.parse("13/10/2013 11:30:55");
String duration = DateTimeUtils.printDifference(date1, date2);
复制代码
public class DateTimeUtils {
public static String printDifference(Date startDate, Date endDate){
long different = endDate.getTime() - startDate.getTime();
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long monthsInMilli = daysInMilli * 30;
long yearsInMilli = daysInMilli * 365;
long elapsedYears = different / yearsInMilli;
if(elapsedYears > 0)
return Long.toString(elapsedYears) + " 年前";
different = different % yearsInMilli;
long elapsedMonths = different / monthsInMilli;
if(elapsedMonths > 0)
return Long.toString(elapsedMonths) + " 月前";
different = different % monthsInMilli;
long elapsedDays = different / daysInMilli;
if(elapsedDays > 0)
return Long.toString(elapsedDays) + " 天前";
different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
if(elapsedHours > 0)
return Long.toString(elapsedHours) + " 小時前";
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
if(elapsedMinutes > 0)
return Long.toString(elapsedMinutes) + " 分鐘前";
different = different % minutesInMilli;
long elapsedSeconds = different / secondsInMilli;
return Long.toString(elapsedSeconds) + " 秒前";
}
}
复制代码
欢迎光临 大马资讯论坛 - 马来西亚中文资讯平台 (http://freeinfo.com.my/)
Powered by Discuz! X3.3