gpt4 book ai didi

java - Calendar.getInstance() 和 GregorianCalendar.getInstance() 之间的区别

转载 作者:搜寻专家 更新时间:2023-10-30 21:09:48 26 4
gpt4 key购买 nike

自从首次引入它来替换 Date 以来,我一直在使用静态方法 Calendar.getInstance() 来获取新的 Calendar目的。我从来没有遇到过问题,但出于某种原因我只是想知道使用 GregorianCalendar.getInstance() 方法是否更好。

我的程序是否有可能在某个地方或某个 JVM 中运行,父类(super class)版本将返回一个我不期望的对象类? Calendar GregorianCalendar 是否曾被广泛使用?

正如我所说,我目前没有遇到任何问题,但我一直在寻求改进我的做法。

最佳答案

是的,Calendar 可以返回特定于语言环境的日历。来自源头。

/**
* Gets a calendar using the default time zone and locale. The
* <code>Calendar</code> returned is based on the current time
* in the default time zone with the default
* {@link Locale.Category#FORMAT FORMAT} locale.
*
* @return a Calendar.
*/
public static Calendar getInstance()
{
return createCalendar(TimeZone.getDefault(), Locale.getDefault(Locale.Category.FORMAT));
}

private static Calendar createCalendar(TimeZone zone,
Locale aLocale)
{
CalendarProvider provider =
LocaleProviderAdapter.getAdapter(CalendarProvider.class, aLocale)
.getCalendarProvider();
if (provider != null) {
try {
return provider.getInstance(zone, aLocale);
} catch (IllegalArgumentException iae) {
// fall back to the default instantiation
}
}

Calendar cal = null;

if (aLocale.hasExtensions()) {
String caltype = aLocale.getUnicodeLocaleType("ca");
if (caltype != null) {
switch (caltype) {
case "buddhist":
cal = new BuddhistCalendar(zone, aLocale);
break;
case "japanese":
cal = new JapaneseImperialCalendar(zone, aLocale);
break;
case "gregory":
cal = new GregorianCalendar(zone, aLocale);
break;
}
}
}
if (cal == null) {
// If no known calendar type is explicitly specified,
// perform the traditional way to create a Calendar:
// create a BuddhistCalendar for th_TH locale,
// a JapaneseImperialCalendar for ja_JP_JP locale, or
// a GregorianCalendar for any other locales.
// NOTE: The language, country and variant strings are interned.
if (aLocale.getLanguage() == "th" && aLocale.getCountry() == "TH") {
cal = new BuddhistCalendar(zone, aLocale);
} else if (aLocale.getVariant() == "JP" && aLocale.getLanguage() == "ja"
&& aLocale.getCountry() == "JP") {
cal = new JapaneseImperialCalendar(zone, aLocale);
} else {
cal = new GregorianCalendar(zone, aLocale);
}
}
return cal;
}

关于java - Calendar.getInstance() 和 GregorianCalendar.getInstance() 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25593768/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com