java計算時間差及比較時間大小

shwenwen發表於2009-04-01

javaz中對日期時間的處理比較多,程式碼中列出了3中日期時間計算差值的方法。

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

[@more@]
java計算時間差及比較時間大小

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

方法一:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

try
{
Date d1 = df.parse("2004-03-26 13:31:40");
Date d2 = df.parse("2004-01-02 11:30:24");
long diff = d1.getTime() - d2.getTime();
long days = diff / (1000 * 60 * 60 * 24);
}
catch (Exception e)
{
}

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

方法三:
SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date begin=dfs.parse("2004-01-02 11:30:24");
java.util.Date end = dfs.parse("2004-03-26 13:31:40");
long between=(end.getTime()-begin.getTime())/1000;//除以1000是為了轉換成秒

long day1=between/(24*3600);
long hour1=between%(24*3600)/3600;
long minute1=between%3600/60;
long second1=between%60/60;
System.out.println(""+day1+"天"+hour1+"小時"+minute1+"分"+second1+"秒");

====================================================

java 比較時間大小

String s1="2008-01-25 09:12:09";
<wbr><wbr><wbr><wbr><wbr><wbr><wbr>String s2
="2008-01-29 09:12:11";
<wbr><wbr><wbr><wbr><wbr><wbr><wbr>java.text.DateFormat df
=new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
<wbr><wbr><wbr><wbr><wbr><wbr><wbr>java.util.Calendar c1
=java.util.Calendar.getInstance();
<wbr><wbr><wbr><wbr><wbr><wbr><wbr>java.util.Calendar c2
=java.util.Calendar.getInstance();
<wbr><wbr><wbr><wbr><wbr><wbr><wbr>
try
<wbr><wbr><wbr><wbr><wbr><wbr><wbr>{
<wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr>c1.setTime(df.parse(s1));
<wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr>c2.setTime(df.parse(s2));
<wbr><wbr><wbr><wbr><wbr><wbr><wbr>}
catch(java.text.ParseException e){
<wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr>System.err.println(
"格式不正確");
<wbr><wbr><wbr><wbr><wbr><wbr><wbr>}
<wbr><wbr><wbr><wbr><wbr><wbr><wbr>
int result=c1.compareTo(c2);
<wbr><wbr><wbr><wbr><wbr><wbr><wbr>
if(result==0)
<wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr>System.out.println(
"c1相等c2");
<wbr><wbr><wbr><wbr><wbr><wbr><wbr>
else if(result<0)
<wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr>System.out.println(
"c1小於c2");
<wbr><wbr><wbr><wbr><wbr><wbr><wbr>
else
<wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr>System.out.println(
"c1大於c2");

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/143526/viewspace-1019703/,如需轉載,請註明出處,否則將追究法律責任。

相關文章