2010-10-18 21 views
31

Ho provato diversi metodi sul Web ma non sono riuscito a farlo funzionare.Differenza Android tra due date in secondi

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"))); 

In questo modo ottengo entrambe le date in un buon formato. Ora voglio trovare la differenza tra EndDate e Startdate in pochi secondi.

Qualche consiglio? Grazie.

risposta

86

È possibile trasformare un oggetto data in una lunga (millisecondi dal 1 gennaio 1970), e quindi utilizzare TimeUnit per ottenere il numero di secondi:

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

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

Edit: -Corrected il nome della variabile diffInMs che è stato scritto diffInM (i) s nella seconda riga.

4

Basta integrare questa risposta per altri sviluppatori (come me) che utilizzano Time anziché 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

prova di seguito il metodo: -

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"; 
     } 
    }