Initialising date with Date(milliseconds) constructor

JavaDoc for Date class states that

public Date(long date)
Allocates a Date object and initializes it to represent the specified number of         
milliseconds since the standard base time known as "the epoch", namely January 1, 1970,   
00:00:00 GMT.

Below is the code which calculates Date for Jan 24th and Jan 25th by calculating the number of milliseconds using Date(long milliSeconds) constructor

public static void main(String[] args) throws java.text.ParseException {

    long milliSecFor25 = (24*60*60*24*1000);
    long milliSecFor26 = (25*60*60*24*1000);
    Date dateJan25 = new Date(milliSecFor25);
    Date dateJan26 = new Date(milliSecFor26);
    System.out.println("Date for Jan 25:" + dateJan25);
    System.out.println("Date for Jan 26:" + dateJan26);
}

On executing the below code i get the below output,

    Date for Jan 25: Sun Jan 25 05:30:00 IST 1970
    Date for Jan 26: Sun Dec 07 12:27:12 IST 1969

which is incorrect. Can someone explain why don`t I get the correct date for Jan 25

Jon Skeet
people
quotationmark

The problem is here:

25*60*60*24*1000

All of this is being performed in integer arithmetic - and that value is overflowing.

You can see that if you perform the arithmetic using long values instead, and show the result compared to Integer.MAX_VALUE:

milliSecFor26 = (25*60*60*24*1000L);
System.out.println("Millis: " + milliSecFor26);
System.out.println("Integer.MAX_VALUE: " + Integer.MAX_VALUE);

Prints:

Millis: 2160000000
Integer.MAX_VALUE: 2147483647

So your int arithmetic is actually overflowing to a negative value, which is why you're seeing a Date value before the Unix epoch.

As asides:

  • You can use TimeUnit.DAYS.toMillis(26) as a much cleaner way of computing this
  • Within the Java standard libraries (pre-Java 8), you should use Calendar to obtain an appropriate Date from a year/month/day
  • Joda Time is a much nicer library than Date/Calendar
  • Java 8 will have an even cleaner date/time API (in the java.time package).

people

See more on this question at Stackoverflow