What happened to the Java Date constructor (long date)?

I have two objects: p4 and p5, which have a Date property. In some cases, the constructor works fine:

p4.setClickDate(new Date(System.currentTimeMillis() - 86400000 * 4)); 

Sets the date Sun Sun Jul 31 11:01:39 EDT 2011

And in other situations, this is not so:

 p5.setClickDate(new Date(System.currentTimeMillis() - 86400000 * 70)); 

Sets the date Fri Jul 15 04:04:26 EDT 2011

According to my calculations, this should set the date to 70 days, no?

I can get around this with Calendar, but I'm curious why Date behaves this way.

Thanks!

+4
source share
2 answers

This is caused by integer overflow. Integers have a maximum value of Integer.MAX_VALUE , which is 2147483647 . You need to explicitly specify the number, which should be long , by suffixing it with L

 p5.setClickDate(new Date(System.currentTimeMillis() - 86400000L * 70)); 

You can see it for yourself by comparing the results.

 System.out.println(86400000 * 70); // 1753032704 System.out.println(86400000L * 70); // 6048000000 

See also:

+12
source

the number is too large and you have an overflow, you must add L to the end to make it long. \ 8640000l (the default java numbers are int)

+3
source

All Articles