1. 程式人生 > >JAVA 計算時間差

JAVA 計算時間差

com con 獲得 () exceptio string ret except span

比如:現在是2004-03-26 13:31:40
過去是:2004-01-02 11:30:24
我現在要獲得兩個日期差,差的形式為:XX天XX小時XX分XX秒
方法一:

 1 DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
 2 try  
 3 {   
 4     Date d1 = df.parse("2004-03-26 13:31:40");   
 5     Date d2 = df.parse("2004-01-02 11:30:24");   
 6     long diff = d1.getTime() - d2.getTime();   
7 long days = diff / (1000 * 60 * 60 * 24); 8 } 9 catch (Exception e) 10 { 11 }

方法二:

1 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
2    java.util.Date now = df.parse("2004-03-26 13:31:40");   
3    java.util.Date date=df.parse("2004-01-02 11:30:24");   
4    long l=now.getTime()-date.getTime();   
5 long day=l/(24*60*60*1000); 6 long hour=(l/(60*60*1000)-day*24); 7 long min=((l/(60*1000))-day*24*60-hour*60); 8 long s=(l/1000-day*24*60*60-hour*60*60-min*60); 9 System.out.println(""+day+"天"+hour+"小時"+min+"分"+s+"秒");

方法三:

1 SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
2 java.util.Date begin=dfs.parse("2004-01-02 11:30:24"); 3 java.util.Date end = dfs.parse("2004-03-26 13:31:40"); 4 long between=(end.getTime()-begin.getTime())/1000;//除以1000是為了轉換成秒 5 long day1=between/(24*3600); 6 long hour1=between%(24*3600)/3600; 7 long minute1=between%3600/60; 8 long second1=between%60/60; 9 System.out.println(""+day1+"天"+hour1+"小時"+minute1+"分"+second1+"秒");

比較時間:

 1 String s1="2008-01-25 09:12:09";   
 2 String s2="2008-01-29 09:12:11";   
 3 java.text.DateFormat df=new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
 4 java.util.Calendar c1=java.util.Calendar.getInstance();   
 5 java.util.Calendar c2=java.util.Calendar.getInstance();   
 6 try  
 7 {   
 8 c1.setTime(df.parse(s1));   
 9 c2.setTime(df.parse(s2));   
10 }catch(java.text.ParseException e){   
11 System.err.println("格式不正確");   
12 }   
13 int result=c1.compareTo(c2);   
14 if(result==0)   
15 System.out.println("c1相等c2");   
16 else if(result<0)   
17 System.out.println("c1小於c2");   
18 else  
19 System.out.println("c1大於c2"); 

JAVA 計算時間差