資源描述:
《java計(jì)算時(shí)間差及比較時(shí)間大小》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在應(yīng)用文檔-天天文庫。
1、java計(jì)算時(shí)間差及比較時(shí)間大小java中對(duì)日期時(shí)間的處理比較多,代碼中列出了3中日期時(shí)間計(jì)算差值的方法。比如:現(xiàn)在是2004-03-2613:31:40過去是:2004-01-0211:30:24我現(xiàn)在要獲得兩個(gè)日期差,差的形式為:XX天XX小時(shí)XX分XX秒java計(jì)算時(shí)間差及比較時(shí)間大小比如:現(xiàn)在是2004-03-2613:31:40過去是:2004-01-0211:30:24我現(xiàn)在要獲得兩個(gè)日期差,差的形式為:XX天XX小時(shí)XX分XX秒方法一:DateFormatdf=newSimpleDateFormat("yyyy-MM-ddHH
2、:mm:ss");try{Dated1=df.parse("2004-03-2613:31:40");Dated2=df.parse("2004-01-0211:30:24");longdiff=d1.getTime()-d2.getTime();longdays=diff/(1000*60*60*24);}catch(Exceptione){}方法二:SimpleDateFormatdf=newSimpleDateFormat("yyyy-MM-ddHH:mm:ss");java.util.Datenow=df.parse("2004-0
3、3-2613:31:40");java.util.Datedate=df.parse("2004-01-0211:30:24");longl=now.getTime()-date.getTime();longday=l/(24*60*60*1000);longhour=(l/(60*60*1000)-day*24);longmin=((l/(60*1000))-day*24*60-hour*60);longs=(l/1000-day*24*60*60-hour*60*60-min*60);System.out.println(""+day+
4、"天"+hour+"小時(shí)"+min+"分"+s+"秒");方法三:SimpleDateFormatdfs=newSimpleDateFormat("yyyy-MM-ddHH:mm:ss");java.util.Datebegin=dfs.parse("2004-01-0211:30:24");java.util.Dateend=dfs.parse("2004-03-2613:31:40");longbetween=(end.getTime()-begin.getTime())/1000;//除以1000是為了轉(zhuǎn)換成秒longday1=bet
5、ween/(24*3600);longhour1=between%(24*3600)/3600;longminute1=between%3600/60;longsecond1=between%60/60;System.out.println(""+day1+"天"+hour1+"小時(shí)"+minute1+"分"+second1+"秒");====================================================java比較時(shí)間大小Strings1="2008-01-2509:12:09";Strings2="20
6、08-01-2909:12:11";java.text.DateFormatdf=newjava.text.SimpleDateFormat("yyyy-MM-ddHH:mm:ss");java.util.Calendarc1=java.util.Calendar.getInstance();java.util.Calendarc2=java.util.Calendar.getInstance();try{c1.setTime(df.parse(s1));c2.setTime(df.parse(s2));}catch(java.text.P
7、arseExceptione){System.err.println("格式不正確");}intresult=c1.compareTo(c2);if(result==0)System.out.println("c1相等c2");elseif(result<0)System.out.println("c1小于c2");elseSystem.out.println("c1大于c2");