bvulaj
bvulaj

Reputation: 5123

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!

Upvotes: 4

Views: 1182

Answers (2)

roni bar yanai
roni bar yanai

Reputation: 1492

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)

Upvotes: 3

BalusC
BalusC

Reputation: 1109152

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:

Upvotes: 12

Related Questions