Possible overflow error through using java.util.Date

This code:

package test; import java.util.Date; public class DateUnderflow { public static void main(String[] args) { Long timestamp = -8120649749785140250L; System.out.println(new Date(timestamp)); } } 

It produces the following output:

 "Sat Aug 03 10:00:59 CET 257325894" 

How did it happen? Exclusion without exception?

Doc says the date Date(long date) parameter is the number of milliseconds since the era, so I'm a little surprised to find that this is far in the future.

My setup:

  • Linux mint 17.1
  • Eclipse Luna Service Release 1a (4.4.1)
  • java7-OpenJDK-amd64
+7
source share
2 answers

RTFM ( manual )

public Date(long date)

Creates a Date object using the given milliseconds. If the specified value in milliseconds contains the time of the information, the driver will set the time components to the time in the default time zone (time zone of the Java virtual machine launching the application), which corresponds to zero GMT.

Options:

date - milliseconds from January 1, 1970, 00:00:00 GMT should not exceed the representation of milliseconds for the year 8099. A negative number indicates the number of milliseconds until January 1, 1970, 00:00:00 GMT.

should not exceed the representation of milliseconds per year 8099


In addition to this, I most likely save time by saying: if you are doing time in java, use the joda time library:

http://www.joda.org/joda-time/

+1
source share

The maximum long value is 9223372036854775807 . If you exceed this maximum value, the next value will be the minimum maximum value.

If you build a date from this maximum value, it will result in a date. How about a date next to this. If you add more than a mile second for the next launches with a minimum long value.

-8120649749785140250 equivalent to 9223372036854775807 + 1102722287069635559

Try System.out.println(9223372036854775807L+1102722287069635559L);

I believe your code is equivalent

 Date d1 = new Date(9223372036854775807L); // Date for max long value Date d2 = new Date(d1.getTime() + 1102722287069635559L); // plus some mili-seconds System.out.println(d2); 

This gives the result you get.

-one
source share

All Articles