1.public class Test {
2.public void dateDiff(String startTime, String endTime, String format) {
3.//按照傳入的格式生成一個(gè)simpledateformate對(duì)象
4.SimpleDateFormat sd = new SimpleDateFormat(format);
5.long nd = 1000*24*60*60;//一天的毫秒數(shù)
6.long nh = 1000*60*60;//一小時(shí)的毫秒數(shù)
7.long nm = 1000*60;//一分鐘的毫秒數(shù)
8.long ns = 1000;//一秒鐘的毫秒數(shù)
9.long diff;
10.try {
11.//獲得兩個(gè)時(shí)間的毫秒時(shí)間差異
12.diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
13.long day = diff/nd;//計(jì)算差多少天
14.long hour = diff%nd/nh;//計(jì)算差多少小時(shí)
15.long min = diff%nd%nh/nm;//計(jì)算差多少分鐘
16.long sec = diff%nd%nh%nm/ns;//計(jì)算差多少秒
17.//輸出結(jié)果
18.System.out.println("時(shí)間相差:"+day+"天"+hour+"小時(shí)"+min+"分鐘"+sec+"秒。");
19.} catch (ParseException e) {
20.e.printStackTrace();
21.}
22.}
23.
24.
25.public static void main(String[] args) {
26.new Test().dateDiff(new SimpleDateFormat("yyyy-MM-dd").format(new Date()), "2010-8-23", "yyyy-MM-dd");
27.}
28.}
更多信息請(qǐng)查看IT技術(shù)專欄