簡體   English   中英

getTimeinMillis給出負值

[英]getTimeinMillis giving a negative value

這是我的約會對象

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();
}

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

startdate = 12:00
enddate = 12:01

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

更換

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識別出來了。

你在這里做的是你在cal1之后調用cal2所以它肯定會比cal1具有更高的值,因為它具有最近的時間,因此是負的結果值。

只需切換它們,然后再試一次:

 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();
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM