我正在开发一个小型闹钟应用程序,我需要一种方法来计算时间差,以便能够将时间间隔传递给 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;
}