2010-10-18 146 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"; 
     } 
    }