Veljko
Veljko

Reputation: 1903

Android get difference in milliseconds between two dates

I have Integer fields:

currentYear,currentMonth,currentDay,currentHour,currentMinute and nextYear,nextMonth,nextDay,nextHour,nextMinute.

How I can get difference between those two spots in time in milliseconds. I found a way using Date() object, but those functions seems to be depricated, so it's little risky.

Any other way?

Upvotes: 6

Views: 8912

Answers (2)

MLQ
MLQ

Reputation: 13511

Create a Calendar object for currenDay and nextDay, turn them into longs, then subtract. For example:

Calendar currentDate = Calendar.getInstance();
Calendar.set(Calendar.MONTH, currentMonth - 1); // January is 0, Feb is 1, etc.
Calendar.set(Calendar.DATE, currentDay);
// set the year, hour, minute, second, and millisecond
long currentDateInMillis = currentDate.getTimeInMillis();

Calendar nextDate = Calendar.getInstance();
// set the month, date, year, hour, minute, second, and millisecond
long nextDateInMillis = nextDate.getTimeInMillis();

return nextDateInMillis - currentDateInMillis; // this is what you want

If you don't like the confusion around the Calendar class, you can check out the Joda time library.

Upvotes: 3

PearsonArtPhoto
PearsonArtPhoto

Reputation: 39698

Use GregorianCalendar to create the date, and take the diff as you otherwise would.

GregorianCalendar currentDay=new  GregorianCalendar (currentYear,currentMonth,currentDay,currentHour,currentMinute,0);
GregorianCalendar nextDay=new  GregorianCalendar (nextYear,nextMonth,nextDay,nextHour,nextMinute,0);

diff_in_ms=nextDay. getTimeInMillis()-currentDay. getTimeInMillis();

Upvotes: 7

Related Questions