Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with the Java Date constructor Date(long date)?

I have two objects, p4 and p5, that have a Date property. At some points, the constructor works fine:

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

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

And in other situations it does not:

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

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

By my calculations, this should set the date back 70 days, no?

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

Thanks!

like image 589
bvulaj Avatar asked Dec 06 '22 20:12

bvulaj


2 Answers

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

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

You can see it yourself by comparing the results of

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

See also:

  • Java Tutorials - Language Basics - Primitive Data Types
like image 87
BalusC Avatar answered Dec 10 '22 11:12

BalusC


the number is too big and you have overflow you should add L at the end to make it long.\8640000l (java numbers are int by default)

like image 40
roni bar yanai Avatar answered Dec 10 '22 12:12

roni bar yanai