2010-10-18 102 views
31

我已经尝试了不同的方法在网络上,但无法使其工作。在两个日期之间的Android差异在几秒钟内

Cursor cursor = sqlite.myDataBase.rawQuery("SELECT StartDate, EndDate FROM Tracks Where Id="+'"'+trackId+'"',null); 

SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
Date startDate = outputFormat.parse(cursor.getString(cursor.getColumnIndex("StartDate"))); 
Date endDate = outputFormat.parse(cursor.getString(cursor.getColumnIndex("EndDate"))); 

以这种方式,我得到了两个日期格式良好的日期。现在我想在几秒钟内找到EndDateStartdate之间的区别。

有什么建议吗?谢谢。

回答

86

你可以把Date对象为长(毫秒自1970年1月1日),然后用TimeUnit获得的秒数:变量的 -Corrected名称:

long diffInMs = endDate.getTime() - startDate.getTime(); 

long diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMs); 

编辑在第二行写入diffInM(i)s的diffInMs。

4

只为使用Time而不是Date的其他开发人员(如我)补充此答案。

Time t1 = new Time(); 
t1.setToNow(); 
Thread.sleep(1000); 

Time t2 = new Time(); 
t2.setToNow(); 

diff = TimeUnit.MILLISECONDS.toSeconds(t2.toMillis(true)-t1.toMillis(true)); 
5

试试下面的方法: -

public String twoDatesBetweenTime(String oldtime) 
    { 
     // TODO Auto-generated method stub 
     int day = 0; 
     int hh = 0; 
     int mm = 0; 
     try 
     { 
      SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
      Date oldDate = dateFormat.parse(oldtime); 
      Date cDate = new Date(); 
      Long timeDiff = cDate.getTime() - oldDate.getTime(); 
      day = (int) TimeUnit.MILLISECONDS.toDays(timeDiff); 
      hh = (int) (TimeUnit.MILLISECONDS.toHours(timeDiff) - TimeUnit.DAYS.toHours(day)); 
      mm = (int) (TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff))); 
     } 
     catch (ParseException e) 
     { 
      e.printStackTrace(); 
     } 
     if(day==0) 
     { 
      return hh + " hour " + mm + " min"; 
     } 
     else if(hh==0) 
     { 
      return mm + " min"; 
     } 
     else 
     { 
      return day + " days " + hh + " hour " + mm + " min"; 
     } 
    }