我正在开发一个小闹钟应用程序,我需要一种方法来计算时间差,以便能够将间隔传递给alarmManager。我在这里看到了很多类似的话题,所以问题是:为我的目的计算时差的最佳方法是什么? 我编写了这个方法来从时间戳中获取时间并计算差异,但是因为我在测试时得到了一些疯狂的值所以它是错误的。
public int CalculateInterval() {
/*--- get the target time from the time picker ---*/
ViewGroup vg = (ViewGroup) tp.getChildAt(0);
ViewGroup number1 = (ViewGroup) vg.getChildAt(0);
ViewGroup number2 = (ViewGroup) vg.getChildAt(1);
String hours = ((EditText) number1.getChildAt(1)).getText()
.toString();
String mins = ((EditText) number2.getChildAt(1)).getText()
.toString();
/*--- convert to integer values in ms ---*/
int hrsInMillis = Integer.parseInt(hours) * 3600 * 1000;
int mnsInMillis = Integer.parseInt(mins) * 60 * 100;
/*--- obtain the current time in ms ---*/
Calendar c = Calendar.getInstance();
int secondsInMillis = c.get(Calendar.SECOND) * 1000;
int minutesInMillis = c.get(Calendar.MINUTE) * 1000 * 60;
int HoursInMillis = c.get(Calendar.HOUR) * 1000 * 3600;
int current = secondsInMillis + minutesInMillis + HoursInMillis;
/*--- calculate the difference ---*/
int interval = (hrsInMillis + mnsInMillis) - current;
return interval;
}
答案 0 :(得分:0)
Calendar c = Calendar.getInstance();
int secondsInMillis = c.get(Calendar.SECOND) * 1000;
int minutesInMillis = c.get(Calendar.MINUTE) * 1000 * 60;
int HoursInMillis = c.get(Calendar.HOUR) * 1000 * 3600;
上面的代码有点不必要了,我猜这就是你获得“疯狂价值”的原因。相反,从long
获取c
值,然后用另一个long
减去它。
然而,这是一个小技巧,因为你目前只能得到毫秒的小时和分钟。
这是我要做的(伪代码):
set alarm to Calendar.getInstance()
set alarm.hour to Integer.parseInt(hours)
set alarm.minute to Integer.parseInt(mins)
set alarm.secs to 0
if alarm.before(now)
add 1 day to alarm
endif
set difference to (alarm.getTimeInMillis() - now.getTimeInMillis())