2014-02-20 46 views
4

這是我迄今爲止getTimeinMillis給負值

Thu Feb 20 18:34:00 GMT+5:30 2014 

當我使用getTimeInMillis()我在歌廳負值(-5856679776000)。這應該是積極的。誰能告訴我爲什麼?

存儲的日期,即cal1給出負值,而第二個日期,即當前日期是正值。

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",java.util.Locale.getDefault()); 
try { 
    java.util.Date d = format.parse(date+" "+time); 
    GregorianCalendar cal1 = new GregorianCalendar(d.getYear(), 
                d.getMonth(), 
                d.getDay(), 
                d.getHours(), 
                d.getMinutes()); 

    Calendar cal = Calendar.getInstance(); 
    GregorianCalendar cal2 = new GregorianCalendar(cal.get(Calendar.YEAR), 
                cal.get(Calendar.MONTH), 
                cal.get(Calendar.DAY_OF_MONTH), 
                cal.get(Calendar.HOUR_OF_DAY), 
                cal.get(Calendar.MINUTE)); 

    Toast.makeText(getApplicationContext(), 
     "Stored date " + d + 
     "\nCurrent date " + cal.getTime() + 
     "\nStored date in ms :" + cal1.getTimeInMillis() + 
     "\nCurrent time in ms :" + cal2.getTimeInMillis()+ 
     "\nDifference " + ((cal1.getTimeInMillis()-cal2.getTimeInMillis())/1000), 
     Toast.LENGTH_LONG).show(); 
} 
catch(Exception e) { 
    Toast.makeText(getApplicationContext(),"Date parsing error", Toast.LENGTH_LONG).show(); 
    e.printStackTrace(); 
} 
+0

'date +'「+ time'中的'date'和'time'是什麼? – fge

+0

'時間'的價值是什麼? – Kedarnath

回答

2

更換

new GregorianCalendar(d.getYear(), d.getMonth(), d.getDay(), d.getHours(), d.getMinutes()); 

new GregorianCalendar(1900+d.getYear(), d.getMonth(), d.getDay(), d.getHours(), d.getMinutes()); 

檢查了getYear方法的文檔。它在1900年後返回......第二個原因已被@Pakspul識別出來。

3

您應該在毫秒計算中交換cal1和cal2。例如:

startdate = 12:00 
enddate = 12:01 

diff = enddate - startdate; // result is 1 minute 
diff = startdate - enddate; // result is -1 minute 
+3

而不是'replace'字'swap'在這種情況下更好, – Kedarnath

+0

cal1.getTimeInMillis()本身就是負面的,因爲它也有差別 –

0

什麼,你是在這裏做的是,你在呼喚吹響---經過CAL2所以它會比吹響--- definatly更高的價值,因爲它具有mostrecent時間,因此陰性結果值。

只需切換並再試一次這樣的:

Toast.makeText(getApplicationContext(),"Stored date "+d+"\nCurrent date "+cal.getTime()+"\nStored date in ms :"+cal1.getTimeInMillis()+"\nCurrent time in ms :"+cal2.getTimeInMillis()+"\nDifference "+((cal2.getTimeInMillis()-cal1.getTimeInMillis())/1000), Toast.LENGTH_LONG).show(); 
    }