Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.util.Date class with different approach for same date gives different output

Tags:

java

public static void main(String[] args) throws ParseException {
    // create a date
    Date date = new Date();
    long diff = date.getTime();
    Date date1 = new Date(2013, 10, 1, 11, 6);
    long diff1 = date1.getTime();
    System.out.println("date is 1-10-2013, " + diff + " have passed.");
    System.out.println("date is 1-10-2013, " + diff1 + " have passed.");
}

and the output is

date is 1-10-2013, 1380605909318 have passed.
date is 1-10-2013, 61341428160000 have passed.

Can anybody elaborate on the difference beween 1380605909318 and 61341428160000?

like image 969
shree18 Avatar asked Oct 01 '13 05:10

shree18


1 Answers

This line:

Date date1 = new Date(2013, 10, 1, 11, 6);

... doesn't do what you thing it does. That creates a Date object representing November 1st in the year 3913, at 11:06 local time. I don't think that's what you wanted.

Indeed, if you change your code to include the date itself rather than hard-coding what you think the right value will be, you'll see that:

System.out.println("date is " + date + ", " + diff + " have passed.");
System.out.println("date is " + date1 + ", " + diff1 + " have passed.");

There's a reason that constructor is deprecated - you should pay attention to deprecation, as well as to the documentation.

Now you could just use java.util.Calendar instead - but I'd actually recommend that you use Joda Time instead, if you possibly can. It's a much, much cleaner API than java.util.Calendar/Date. Alternative, if you can use a pre-release of Java 8, that has the new JSR-320 date/time API.

like image 145
Jon Skeet Avatar answered Sep 24 '22 14:09

Jon Skeet