2012-03-20 60 views
2

我正在嘗試使用開始時間和結束時間,並計算當前時間的百分比(位於startHour和endHour之間)。 例如,如果時間現在是12:00,startHour = 11:00和End Hour = 14:00,則應返回33(四捨五入),因爲33%的時間已過。如何在android中比較已知小時和當前小時?

我曾嘗試以下,但可能是我混合不同的格式...我不知道:

double currentTime = Calendar.getInstance().getTimeInMillis(); 
double startTime = Time.UTC(2012, 3, 20, 22, 0, 0); 
double endTime = Time.UTC(2012, 3, 20, 23, 30, 0); 
int prg = (int)((currentTime - startTime)/(endTime - startTime)); 
在此代碼

我認爲當前的小時22:00 23之間: 30

感謝 的Eyal

+0

那麼,出了什麼問題? – Egor 2012-03-20 21:47:51

+0

它返回一個負數 – Eyal 2012-03-20 21:53:58

+0

開始和結束時間大約是6.1E12,而當前時間是1E13 ... – Eyal 2012-03-20 21:56:22

回答

0

我已經盡了自己和發現錯誤,而讓時間以毫秒爲當前時間日曆實例。

你越來越錯誤,因爲時間milisecond爲CURRENTTIME是不準確的,它是越野車不知何故並爲代表比目前少1個月的時間所以這就是爲什麼你在性否定獲得答案。

您可以通過以下方式執行此操作。

Calendar calCurr = Calendar.getInstance(); 
    Log.i("Time in mili of Current - Normal", ""+calCurr.getTimeInMillis()); // see what it gives? dont know why? 
    Date date = new Date(); 
    calCurr.set(date.getYear()+1900, date.getMonth()+1, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());// so added one month to it 
    Log.i("Time in mili of Current - after update", ""+calCurr.getTimeInMillis()); // now get correct 

    Calendar start = Calendar.getInstance(); 
    start.set(2012, 12, 1, 11, 28, 0); 

    Calendar end = Calendar.getInstance(); 
    end.set(2012, 12, 1, 13, 28, 0); 

    if((start.compareTo(calCurr)==-1) && (calCurr.compareTo(end)==-1) && (start.compareTo(end)==-1)) 
    { 

    double hrBetweenStartEnd = (end.getTimeInMillis()-start.getTimeInMillis())/3600000; 
    double hrBetweenStartCurr = (calCurr.getTimeInMillis()-start.getTimeInMillis())/3600000; 

    int percentage = (int) ((100*hrBetweenStartCurr)/hrBetweenStartEnd); 
    Log.i("Percentage", ""+percentage); 
    } 
0

我不編程機器人,但我很確定問題是,月份是基於零(1月= 0),即3不是3月但是4月。

Time.UTC(2012, 3, 20, 22, 0, 0)不代表3月20日的22:00,但是4月20日。所以目前的時間大約是那個時候的一個月。