getTimeinMillis给出负值

时间:2014-02-20 12:20:13

标签: java android

这是我的约会

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

3 个答案:

答案 0 :(得分:3)

您应该在毫秒计算中交换cal1和cal2。例如:

startdate = 12:00
enddate = 12:01

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

答案 1 :(得分:3)

替换

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确定..

答案 2 :(得分:0)

你在这里做的是你在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();
    }