2012-10-29 68 views
0

我正在開發一個小鬧鐘應用程序,我需要一種計算時間差的方法,以便能夠將間隔傳遞給alarmManager。我在這裏看到很多類似的主題,所以問題是:爲我的目的計算時差的最佳方法是什麼? 我寫的方法從timepicker獲取時間和計算的區別,但它的馬車,因爲我得到一些瘋狂的值,而測試..android計算設置鬧鐘的時間差

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

使用Calendar.set和Calendar.getTimeInMillis() – njzk2

回答

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; 

上面的代碼是有點多餘,我猜想這就是爲什麼你會得到「瘋狂的價值」。相反,從c獲得long的值,並將其與另一個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())