What might be the difference between getting datetime using
Calendar.getInstance()
vs
new GregorianCalendar()
?
Calendar 's getInstance method returns a Calendar object whose calendar fields have been initialized with the current date and time: Calendar rightNow = Calendar.
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.
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.
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.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With