GetTimeinMillis gives a negative value

This is my date

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

When I use getTimeInMillis (), I get a negative value (-5856679776000). It must be something positive. Can someone tell me why?

The stored date ie cal1 gives a negative value, and the second date ie the current date is positive.

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();
}
+4
source share
3 answers

replace

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

from

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

Check the documentation of the getYear method. It returns years after 1900 ... And the second reason has already been identified by @Pakspul ..

+2
source

You must exchange cal1 and cal2 for calculations in milliseconds. For example:

startdate = 12:00
enddate = 12:01

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

What you are doing here is that you call cal2 after cal1, so it will have a higher value than cal1 because it has the longest time, hence the negative value of the result.

just switch them and try again as follows:

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

Source: https://habr.com/ru/post/1527890/


All Articles