Get date and time per day, hours, minutes and seconds in Android

I need to get the difference between the current date and the future date, in days, hours, minutes and seconds in Android. For example, if the current date and time is 05/17/2012 03:53:00, and the date in the future is 05/18/2012 04:55:00.

I need to display the difference as the remaining time = day: 1, hours: 1 and minutes 2.

Any help would be greatly appreciated. Thank you very much in advance.

Regards, Munazza K

+5
source share
5 answers

You can do it

   c_date=18/05/2012 04:55:00.  and  saved_date=17/05/2012 03:53:00

   long diffInMillisec = c_date.getTime() -saved_date.getTime();
   long diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMillisec);
   seconds = diffInSec % 60;
   diffInSec/= 60;
   minutes =diffInSec % 60;
   diffInSec /= 60;
   hours = diffInSec % 24;
   diffInSec /= 24;
   days = diffInSec;`
+16
source

You can subtract both dates and calculate the differences. Kind:

long difference = calendar.getTimeInMillis()-currentTime;

    long x = difference / 1000;
    seconds = x % 60;
    x /= 60;
    minutes = x % 60;
    x /= 60;
    hours = x % 24;
    x /= 24;
    days = x;

You can subtract the time that you have already calculated. You get hours, get everything else, do minutes, etc.

+8
source

, JodaTime. Android : http://joda-time.sourceforge.net/

//Create your taget date    
Calendar cal = Calendar.getInstance();
    cal.clear();
    cal.set(Calendar.YEAR, 2012);
    cal.set(Calendar.MONTH, Calendar.JULY);
    cal.set(Calendar.DATE, 15);
    cal.set(Calendar.HOUR_OF_DAY, 8);
    Date startDate = cal.getTime();

//Use JodaTime to calculate difference
    Period period =  getTimePassedSince(startDate);

//Extract values and display
    daysTV.setText("" + Math.abs(period.getDays()));
    hoursTV.setText("" + Math.abs(period.getHours()));
    minsTV.setText("" + Math.abs(period.getMinutes()));
    secsTV.setText("" + Math.abs(period.getSeconds()));

    ...
    public static Period getTimePassedSince(Date initialTimestamp){
            DateTime initDT = new DateTime(initialTimestamp.getTime());
            DateTime now = new DateTime();
            Period p = new Period(initDT, now, PeriodType.dayTime()).normalizedStandard( PeriodType.dayTime());
            return p;
        }
+1

Date .

getTime() 2 . Date . , Date.

0

All Articles