6

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?

4

2 回答 2

6

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();
于 2012-11-18T02:20:01.753 回答
3

为and创建一个Calendar对象,将它们变成长整数,然后减去。例如:currenDaynextDay

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

如果您不喜欢Calendar课堂上的混乱,可以查看 Joda 时间库。

于 2012-11-18T02:42:25.417 回答