Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android get difference in milliseconds between two dates

Tags:

java

date

android

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?

like image 858
Veljko Avatar asked Nov 18 '12 02:11

Veljko


2 Answers

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();
like image 95
PearsonArtPhoto Avatar answered Sep 30 '22 21:09

PearsonArtPhoto


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.

like image 23
MLQ Avatar answered Sep 30 '22 19:09

MLQ