Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Calendar.getInstance().getTime() ever going to give me a different answer than new Date()?

Tags:

java

I'm trying to consolidate some code that is very messy but I want to make sure I don't break things. In some places I see a date created as Calendar.getInstance().getTime() and in others it's just new Date(). Will it break things if I convert them all to new Date() or is there some reason I may want to use the other?

like image 675
Rocky Pulley Avatar asked Aug 14 '12 20:08

Rocky Pulley


2 Answers

In theory, no, because both java.util.Date and java.util.Calendar.getInstance() eventually use System.currentTimeMillis() to return the current time.

The Calendar implementation, however, takes other things into consideration, like the Locale, or if the locale is JP or TH... you can see that in the source code of both classes.

like image 165
Filipe Fedalto Avatar answered Oct 15 '22 14:10

Filipe Fedalto


I think both will return same :

Calendar.getInstance().getTime() : Returns a Date object representing this Calendar's time value (millisecond offset from the Epoch(January 1, 1970 00:00:00.000 GMT (Gregorian).)").

new Date() : internally uses System.currentTimeMillis(), Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond. the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.

I checked like :

public static void main(String[] args) {
    Date date = new Date();
    Date date1 = Calendar.getInstance().getTime();

    System.out.println(date +" = " + date1);

}

Output :

Wed Aug 15 02:45:15 IST 2012 = Wed Aug 15 02:45:15 IST 2012
like image 21
Nandkumar Tekale Avatar answered Oct 15 '22 14:10

Nandkumar Tekale