我有整数字段:
currentYear,currentMonth,currentDay,currentHour,currentMinute和nextYear,nextMonth,nextDay,nextHour,nextMinute。
如何以毫秒为单位及时获得这两个点之间的差异。 我找到了一种使用Date()对象的方法,但是这些函数似乎被删除了,所以风险很小。
还有其他方式吗?
答案 0 :(得分:5)
使用GregorianCalendar创建日期,然后按照原样使用差异。
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();
答案 1 :(得分:3)
为Calendar
和currenDay
创建一个nextDay
对象,将其转换为long,然后减去。例如:
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时间库。