0

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

1 回答 1

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;

上面的代码有点不必要,我猜这就是你得到“疯狂值”的原因。取而代之的是,从中获取longc并用另一个减去它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())
于 2012-10-29T15:20:55.097 回答