Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting current datetime using Calendar.getInstance() vs new GregorianCalendar()

What might be the difference between getting datetime using

Calendar.getInstance()

vs

new GregorianCalendar()

?

like image 617
Oh Chin Boon Avatar asked Aug 01 '11 22:08

Oh Chin Boon


People also ask

What is the use of Calendar getInstance () in Java?

Calendar 's getInstance method returns a Calendar object whose calendar fields have been initialized with the current date and time: Calendar rightNow = Calendar.

What is difference between Java Date and Calendar classes?

The difference between Date and Calendar is that Date class operates with specific instant in time and Calendar operates with difference between two dates. The Calendar class gives you possibility for converting between a specific instant in time and a set of calendar fields such as HOUR, YEAR, MONTH, DAY_OF_MONTH.

How does Gregorian calendar compare to date in Java?

equals() method compares this GregorianCalendar to the specified Object. The result is true if and only if the argument is a GregorianCalendar object that represents the same time value (millisecond offset from the Epoch) under the same Calendar parameters and Gregorian change date as this object.

What is Calendar class and Gregorian calendar in Java?

Java 8Object Oriented ProgrammingProgramming. GregorianCalendar is a hybrid calendar that supports both the Julian and Gregorian calendar systems with the support of a single discontinuity, which corresponds by default to the Gregorian date when the Gregorian calendar was instituted.


2 Answers

Looking in the source of Calendar.getInstance():

private static Calendar createCalendar(TimeZone zone, Locale aLocale) {     // If the specified locale is a Thai locale, returns a BuddhistCalendar     // instance.     if ("th".equals(aLocale.getLanguage())         && ("TH".equals(aLocale.getCountry()))) {         return new sun.util.BuddhistCalendar(zone, aLocale);     } else if ("JP".equals(aLocale.getVariant())         && "JP".equals(aLocale.getCountry())         && "ja".equals(aLocale.getLanguage())) {         return new JapaneseImperialCalendar(zone, aLocale);     }             // else create the default calendar     return new GregorianCalendar(zone, aLocale);     } 

So getInstance() will return a Calendar based on your default Locale and TimeZone.

like image 138
user802421 Avatar answered Sep 30 '22 00:09

user802421


Calendar.getInstance() will give you a Calendar using the default time zone and locale, which can result in a GregorianCalendar, a BuddhistCalendar, or a JapaneseImperialCalendar.

GregorianCalendar will always give you, well, a Gregorian calendar.

like image 25
João Silva Avatar answered Sep 30 '22 00:09

João Silva