2010-10-18 29 views
31

He intentado diferentes métodos en la web, pero no pude hacerlo funcionar.Android diferencia entre dos fechas en segundos

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

De esta manera consigo ambas fechas en buen formato. Ahora quiero encontrar la diferencia entre EndDate y Startdate en segundos.

¿Algún consejo? Gracias.

Respuesta

86

usted puede convertir un objeto de fecha en un largo (milisegundos desde ene 1, 1970), y luego usar TimeUnit para obtener el número de segundos:

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

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

Editar: -Corregido el nombre de la variable diffInMs que se escribió diffInM (i) s en la segunda línea.

4

Simplemente complementando esta respuesta para otros desarrolladores (como yo) que están usando Time en lugar de 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

intento por debajo método: -

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