使用行事曆Work with calendars

雖然日期和時間值代表一個時間點,但是其字串表示區分文化特性,而且同時取決於用於顯示特定文化特性之日期和時間值的慣例,以及該文化特性所使用的曆法。Although a date and time value represents a moment in time, its string representation is culture-sensitive and depends both on the conventions used for displaying date and time values by a specific culture and on the calendar used by that culture. 本主題將探討在 .NET 中行事曆的支援,並討論行事曆類別在處理日期值時的使用方式。This topic explores the support for calendars in .NET and discusses the use of the calendar classes when working with date values.

.NET 中的行事曆Calendars in .NET

.NET 中的所有行事曆都衍生自 System.Globalization.Calendar 類別,它會提供基本行事曆的執行。All calendars in .NET derive from the System.Globalization.Calendar class, which provides the base calendar implementation. 其中一個衍生自 Calendar 類別的類別是 EastAsianLunisolarCalendar 類別,其為所有陰陽曆的基底類別。One of the classes that inherits from the Calendar class is the EastAsianLunisolarCalendar class, which is the base class for all lunisolar calendars. .NET 包含下列行事曆實現:.NET includes the following calendar implementations:

曆法的使用方式有兩種:A calendar can be used in one of two ways:

  • 做為特定文化特性使用的曆法。As the calendar used by a specific culture. 每個 CultureInfo 物件都有現行的曆法,也就是物件目前使用的曆法。Each CultureInfo object has a current calendar, which is the calendar that the object is currently using. 所有日期和時間值的字串表示都會自動反映目前的文化特性及其現行曆法。The string representations of all date and time values automatically reflect the current culture and its current calendar. 通常現行曆法是文化特性的預設曆法。Typically, the current calendar is the culture's default calendar. CultureInfo 物件也有選擇性的行事曆,其中包括文化特性可以使用的其他行事曆。CultureInfo objects also have optional calendars, which include additional calendars that the culture can use.

  • 做為與特定文化特性無關的獨立曆法。As a standalone calendar independent of a specific culture. 這種情況下會使用 Calendar 方法以反映曆法的值表達日期。In this case, Calendar methods are used to express dates as values that reflect the calendar.

請注意,這六種曆法類別 ChineseLunisolarCalendarJapaneseLunisolarCalendarJulianCalendarKoreanLunisolarCalendarPersianCalendarTaiwanLunisolarCalendar 只能做為獨立曆法使用。Note that six calendar classes – ChineseLunisolarCalendar, JapaneseLunisolarCalendar, JulianCalendar, KoreanLunisolarCalendar, PersianCalendar, and TaiwanLunisolarCalendar – can be used only as standalone calendars. 這些類別不會由任何文化特性做為預設曆法或選擇性曆法使用。They are not used by any culture as either the default calendar or as an optional calendar.

行事曆和文化特性Calendars and cultures

每一種文化特性都有預設曆法,該曆法是由 CultureInfo.Calendar 屬性所定義。Each culture has a default calendar, which is defined by the CultureInfo.Calendar property. CultureInfo.OptionalCalendars 屬性會傳回 Calendar 物件的陣列,該陣列會指定特定文化特性支援的所有曆法,包括該文化特性的預設曆法。The CultureInfo.OptionalCalendars property returns an array of Calendar objects that specifies all the calendars supported by a particular culture, including that culture's default calendar.

下列範例說明 CultureInfo.CalendarCultureInfo.OptionalCalendars 屬性。The following example illustrates the CultureInfo.Calendar and CultureInfo.OptionalCalendars properties. 範例中會為泰文 (泰國) 和日文 (日本) 文化特性建立 CultureInfo 物件,並且顯示其預設和選擇性曆法。It creates CultureInfo objects for the Thai (Thailand) and Japanese (Japan) cultures and displays their default and optional calendars. 請注意,在這兩種情況下,文化特性的預設曆法也會包含在 CultureInfo.OptionalCalendars 集合中。Note that in both cases, the culture's default calendar is also included in the CultureInfo.OptionalCalendars collection.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      // Create a CultureInfo for Thai in Thailand.
      CultureInfo th = CultureInfo.CreateSpecificCulture("th-TH");
      DisplayCalendars(th);

      // Create a CultureInfo for Japanese in Japan.
      CultureInfo ja = CultureInfo.CreateSpecificCulture("ja-JP");
      DisplayCalendars(ja);
   }

   static void DisplayCalendars(CultureInfo ci)
   {
      Console.WriteLine("Calendars for the {0} culture:", ci.Name);

      // Get the culture's default calendar.
      Calendar defaultCalendar = ci.Calendar;
      Console.Write("   Default Calendar: {0}", GetCalendarName(defaultCalendar));      

      if (defaultCalendar is GregorianCalendar)
         Console.WriteLine(" ({0})", 
                           ((GregorianCalendar) defaultCalendar).CalendarType);
      else
         Console.WriteLine();
      
      // Get the culture's optional calendars.
      Console.WriteLine("   Optional Calendars:");      
      foreach (var optionalCalendar in ci.OptionalCalendars) {
         Console.Write("{0,6}{1}", "", GetCalendarName(optionalCalendar));
         if (optionalCalendar is GregorianCalendar)
            Console.Write(" ({0})", 
                          ((GregorianCalendar) optionalCalendar).CalendarType);

         Console.WriteLine();
      }
      Console.WriteLine();
   }

   static string GetCalendarName(Calendar cal)
   {
      return cal.ToString().Replace("System.Globalization.", "");
   }
}
// The example displays the following output:
//       Calendars for the th-TH culture:
//          Default Calendar: ThaiBuddhistCalendar
//          Optional Calendars:
//             ThaiBuddhistCalendar
//             GregorianCalendar (Localized)
//       
//       Calendars for the ja-JP culture:
//          Default Calendar: GregorianCalendar (Localized)
//          Optional Calendars:
//             GregorianCalendar (Localized)
//             JapaneseCalendar
//             GregorianCalendar (USEnglish)
Imports System.Globalization

Public Module Example
   Public Sub Main()
      ' Create a CultureInfo for Thai in Thailand.
      Dim th As CultureInfo = CultureInfo.CreateSpecificCulture("th-TH")
      DisplayCalendars(th)

      ' Create a CultureInfo for Japanese in Japan.
      Dim ja As CultureInfo = CultureInfo.CreateSpecificCulture("ja-JP")
      DisplayCalendars(ja)
   End Sub

   Sub DisplayCalendars(ci As CultureInfo)
      Console.WriteLine("Calendars for the {0} culture:", ci.Name)

      ' Get the culture's default calendar.
      Dim defaultCalendar As Calendar = ci.Calendar
      Console.Write("   Default Calendar: {0}", GetCalendarName(defaultCalendar))      

      If TypeOf defaultCalendar Is GregorianCalendar Then
         Console.WriteLine(" ({0})", 
                           CType(defaultCalendar, GregorianCalendar).CalendarType)
      Else
         Console.WriteLine()
      End If
      
      ' Get the culture's optional calendars.
      Console.WriteLine("   Optional Calendars:")      
      For Each optionalCalendar In ci.OptionalCalendars
         Console.Write("{0,6}{1}", "", GetCalendarName(optionalCalendar))
         If TypeOf optionalCalendar Is GregorianCalendar Then
            Console.Write(" ({0})", 
                          CType(optionalCalendar, GregorianCalendar).CalendarType)
         End If
         Console.WriteLine()
      Next
      Console.WriteLine()
   End Sub

   Function GetCalendarName(cal As Calendar) As String
      Return cal.ToString().Replace("System.Globalization.", "")
   End Function
End Module
' The example displays the following output:
'       Calendars for the th-TH culture:
'          Default Calendar: ThaiBuddhistCalendar
'          Optional Calendars:
'             ThaiBuddhistCalendar
'             GregorianCalendar (Localized)
'       
'       Calendars for the ja-JP culture:
'          Default Calendar: GregorianCalendar (Localized)
'          Optional Calendars:
'             GregorianCalendar (Localized)
'             JapaneseCalendar
'             GregorianCalendar (USEnglish)

特定 CultureInfo 物件目前使用的曆法是由文化特性的 DateTimeFormatInfo.Calendar 屬性定義。The calendar currently in use by a particular CultureInfo object is defined by the culture's DateTimeFormatInfo.Calendar property. 文化特性的 DateTimeFormatInfo 物件是由 CultureInfo.DateTimeFormat 屬性所傳回。A culture's DateTimeFormatInfo object is returned by the CultureInfo.DateTimeFormat property. 建立文化特性時,其預設值與 CultureInfo.Calendar 屬性的值相同。When a culture is created, its default value is the same as the value of the CultureInfo.Calendar property. 不過,您可以將文化特性的現行曆法變更為 CultureInfo.OptionalCalendars 屬性所傳回陣列中包含的任何曆法。However, you can change the culture's current calendar to any calendar contained in the array returned by the CultureInfo.OptionalCalendars property. 如果您嘗試將現行曆法設定為不包括在 CultureInfo.OptionalCalendars 屬性值中的曆法,則會顯示 ArgumentExceptionIf you try to set the current calendar to a calendar that is not included in the CultureInfo.OptionalCalendars property value, an ArgumentException is thrown.

下列範例會變更阿拉伯文 (沙烏地阿拉伯) 文化特性使用的曆法。The following example changes the calendar used by the Arabic (Saudi Arabia) culture. 首先會具現化 DateTime 值,並且使用現行文化特性 (此案例中是英文 (美國)) 和目前文化特性的曆法 (此案例中是西曆) 顯示該值。It first instantiates a DateTime value and displays it using the current culture - which, in this case, is English (United States) - and the current culture's calendar (which, in this case, is the Gregorian calendar). 接著會將目前的文化特性變更為阿拉伯文 (沙烏地阿拉伯),並且使用其預設的 Um Al-Qura 曆法顯示日期。Next, it changes the current culture to Arabic (Saudi Arabia) and displays the date using its default Um Al-Qura calendar. 最後呼叫 CalendarExists 方法,判斷阿拉伯文 (沙烏地阿拉伯) 文化特性是否支援回曆。It then calls the CalendarExists method to determine whether the Hijri calendar is supported by the Arabic (Saudi Arabia) culture. 由於支援此曆法,因此會將現行曆法變更為回曆,並且再次顯示日期。Because the calendar is supported, it changes the current calendar to Hijri and again displays the date. 請注意,在各案例中,日期會使用目前文化特性的現行曆法顯示。Note that in each case, the date is displayed using the current culture's current calendar.

using System;
using System.Globalization;
using System.Threading;

public class Example
{
   public static void Main()
   {
      DateTime date1 = new DateTime(2011, 6, 20);

      DisplayCurrentInfo();
      // Display the date using the current culture and calendar.
      Console.WriteLine(date1.ToString("d"));       
      Console.WriteLine();
      
      CultureInfo arSA = CultureInfo.CreateSpecificCulture("ar-SA");
      
      // Change the current culture to Arabic (Saudi Arabia).
      Thread.CurrentThread.CurrentCulture = arSA;
      // Display date and information about the current culture.
      DisplayCurrentInfo();
      Console.WriteLine(date1.ToString("d"));
      Console.WriteLine();
      
      // Change the calendar to Hijri.
      Calendar hijri = new HijriCalendar();
      if (CalendarExists(arSA, hijri)) {
         arSA.DateTimeFormat.Calendar = hijri;
         // Display date and information about the current culture.
         DisplayCurrentInfo();
         Console.WriteLine(date1.ToString("d"));
      }       
   }

   private static void DisplayCurrentInfo()
   {
      Console.WriteLine("Current Culture: {0}", 
                        CultureInfo.CurrentCulture.Name);
      Console.WriteLine("Current Calendar: {0}", 
                        DateTimeFormatInfo.CurrentInfo.Calendar);
   }

   private static bool CalendarExists(CultureInfo culture, Calendar cal)
   {
      foreach (Calendar optionalCalendar in culture.OptionalCalendars)
         if (cal.ToString().Equals(optionalCalendar.ToString())) 
            return true;

      return false;
   }
}
// The example displays the following output:
//    Current Culture: en-US
//    Current Calendar: System.Globalization.GregorianCalendar
//    6/20/2011
//    
//    Current Culture: ar-SA
//    Current Calendar: System.Globalization.UmAlQuraCalendar
//    18/07/32
//    
//    Current Culture: ar-SA
//    Current Calendar: System.Globalization.HijriCalendar
//    19/07/32
Imports System.Globalization
Imports System.Threading

Module Example
   Public Sub Main()
      Dim date1 As Date = #6/20/2011#

      DisplayCurrentInfo()
      ' Display the date using the current culture and calendar.
      Console.WriteLine(date1.ToString("d"))       
      Console.WriteLine()
      
      Dim arSA As CultureInfo = CultureInfo.CreateSpecificCulture("ar-SA")
      
      ' Change the current culture to Arabic (Saudi Arabia).
      Thread.CurrentThread.CurrentCulture = arSA
      ' Display date and information about the current culture.
      DisplayCurrentInfo()
      Console.WriteLine(date1.ToString("d"))
      Console.WriteLine()
      
      ' Change the calendar to Hijri.
      Dim hijri As Calendar = New HijriCalendar()
      If CalendarExists(arSA, hijri) Then
         arSA.DateTimeFormat.Calendar = hijri
         ' Display date and information about the current culture.
         DisplayCurrentInfo()
         Console.WriteLine(date1.ToString("d"))
      End If       
   End Sub
   
   Private Sub DisplayCurrentInfo()
      Console.WriteLine("Current Culture: {0}", 
                        CultureInfo.CurrentCulture.Name)
      Console.WriteLine("Current Calendar: {0}", 
                        DateTimeFormatInfo.CurrentInfo.Calendar)
   End Sub

   Private Function CalendarExists(ByVal culture As CultureInfo, 
                                   cal As Calendar) As Boolean
      For Each optionalCalendar As Calendar In culture.OptionalCalendars
         If cal.ToString().Equals(optionalCalendar.ToString()) Then Return True
      Next   
      Return False
   End Function
End Module
' The example displays the following output:
'    Current Culture: en-US
'    Current Calendar: System.Globalization.GregorianCalendar
'    6/20/2011
'    
'    Current Culture: ar-SA
'    Current Calendar: System.Globalization.UmAlQuraCalendar
'    18/07/32
'    
'    Current Culture: ar-SA
'    Current Calendar: System.Globalization.HijriCalendar
'    19/07/32

日期和行事曆Dates and calendars

除了包括 Calendar 類型的參數且允許日期的項目 (也就是月、日和年) 以指定的曆法反映值的建構函式之外,DateTimeDateTimeOffset 這兩個值永遠以西曆為主。With the exception of the constructors that include a parameter of type Calendar and allow the elements of a date (that is, the month, the day, and the year) to reflect values in a designated calendar, both DateTime and DateTimeOffset values are always based on the Gregorian calendar. 例如,這表示 DateTime.Year 屬性會傳回西曆的年,而 DateTime.Day 屬性會傳回西曆的月份日期。This means, for example, that the DateTime.Year property returns the year in the Gregorian calendar, and the DateTime.Day property returns the day of the month in the Gregorian calendar.

重要

務必記得,日期值及其字串表示之間有一項差異。It is important to remember that there is a difference between a date value and its string representation. 前者是以西曆為主,後者是以特定文化特性的現行曆法為主。The former is based on the Gregorian calendar; the latter is based on the current calendar of a specific culture.

下列範例會說明 DateTime 屬性及其對應的 Calendar 方法之間的這項差異。The following example illustrates this difference between DateTime properties and their corresponding Calendar methods. 在此範例中,目前文化特性為阿拉伯文 (埃及),而現行曆法為 Um Al Qura。In the example, the current culture is Arabic (Egypt), and the current calendar is Um Al Qura. DateTime 值會設定為 2011 年第七個月的第 15 天。A DateTime value is set to the fifteenth day of the seventh month of 2011. 很清楚這個日期是解譯為西曆日期,因為這些相同值是 DateTime.ToString(String, IFormatProvider) 方法在使用不因文化特性而異的慣例時所傳回。It is clear that this is interpreted as a Gregorian date, because these same values are returned by the DateTime.ToString(String, IFormatProvider) method when it uses the conventions of the invariant culture. 使用目前文化特性格式化之日期的字串表示為 14/08/32,其為 Um Al Qura 曆法的同等日期。The string representation of the date that is formatted using the conventions of the current culture is 14/08/32, which is the equivalent date in the Um Al Qura calendar. 其次,DateTimeCalendar 的成員會用來傳回 DateTime 值的日、月和年。Next, members of DateTime and Calendar are used to return the day, the month, and the year of the DateTime value. 在各案例中,DateTime 成員傳回的值會反映西曆的值,而 UmAlQuraCalendar 成員傳回的值則會反映 Uum al-Qura 曆法的值。In each case, the values returned by DateTime members reflect values in the Gregorian calendar, whereas values returned by UmAlQuraCalendar members reflect values in the Uum al-Qura calendar.

using System;
using System.Globalization;
using System.Threading;

public class Example
{
   public static void Main()
   {
      // Make Arabic (Egypt) the current culture 
      // and Umm al-Qura calendar the current calendar. 
      CultureInfo arEG = CultureInfo.CreateSpecificCulture("ar-EG");
      Calendar cal = new UmAlQuraCalendar();
      arEG.DateTimeFormat.Calendar = cal;
      Thread.CurrentThread.CurrentCulture = arEG;

      // Display information on current culture and calendar.
      DisplayCurrentInfo();      

      // Instantiate a date object.
      DateTime date1 = new DateTime(2011, 7, 15);

      // Display the string representation of the date.
      Console.WriteLine("Date: {0:d}", date1);
      Console.WriteLine("Date in the Invariant Culture: {0}", 
                        date1.ToString("d", CultureInfo.InvariantCulture));
      Console.WriteLine();
            
      // Compare DateTime properties and Calendar methods.
      Console.WriteLine("DateTime.Month property: {0}", date1.Month);
      Console.WriteLine("UmAlQura.GetMonth: {0}", 
                        cal.GetMonth(date1));
      Console.WriteLine();

      Console.WriteLine("DateTime.Day property: {0}", date1.Day);
      Console.WriteLine("UmAlQura.GetDayOfMonth: {0}", 
                        cal.GetDayOfMonth(date1));                         
      Console.WriteLine();
      
      Console.WriteLine("DateTime.Year property: {0:D4}", date1.Year);
      Console.WriteLine("UmAlQura.GetYear: {0}", 
                        cal.GetYear(date1));                         
      Console.WriteLine();
   }

   private static void DisplayCurrentInfo()
   {
      Console.WriteLine("Current Culture: {0}", 
                        CultureInfo.CurrentCulture.Name);
      Console.WriteLine("Current Calendar: {0}", 
                        DateTimeFormatInfo.CurrentInfo.Calendar);
   }
}
// The example displays the following output:
//    Current Culture: ar-EG
//    Current Calendar: System.Globalization.UmAlQuraCalendar
//    Date: 14/08/32
//    Date in the Invariant Culture: 07/15/2011
//    
//    DateTime.Month property: 7
//    UmAlQura.GetMonth: 8
//    
//    DateTime.Day property: 15
//    UmAlQura.GetDayOfMonth: 14
//    
//    DateTime.Year property: 2011
//    UmAlQura.GetYear: 1432
Imports System.Globalization
Imports System.Threading

Module Example
   Public Sub Main()
      ' Make Arabic (Egypt) the current culture 
      ' and Umm al-Qura calendar the current calendar. 
      Dim arEG As CultureInfo = CultureInfo.CreateSpecificCulture("ar-EG")
      Dim cal As Calendar = New UmAlQuraCalendar()
      arEG.DateTimeFormat.Calendar = cal
      Thread.CurrentThread.CurrentCulture = arEG

      ' Display information on current culture and calendar.
      DisplayCurrentInfo()      

      ' Instantiate a date object.
      Dim date1 As Date = #07/15/2011#

      ' Display the string representation of the date.
      Console.WriteLine("Date: {0:d}", date1)
      Console.WriteLine("Date in the Invariant Culture: {0}", 
                        date1.ToString("d", CultureInfo.InvariantCulture))
      Console.WriteLine()
            
      ' Compare DateTime properties and Calendar methods.
      Console.WriteLine("DateTime.Month property: {0}", date1.Month)
      Console.WriteLine("UmAlQura.GetMonth: {0}", 
                        cal.GetMonth(date1))
      Console.WriteLine()

      Console.WriteLine("DateTime.Day property: {0}", date1.Day)
      Console.WriteLine("UmAlQura.GetDayOfMonth: {0}", 
                        cal.GetDayOfMonth(date1))                         
      Console.WriteLine()
      
      Console.WriteLine("DateTime.Year property: {0:D4}", date1.Year)
      Console.WriteLine("UmAlQura.GetYear: {0}", 
                        cal.GetYear(date1))                         
      Console.WriteLine()
   End Sub
   
   Private Sub DisplayCurrentInfo()
      Console.WriteLine("Current Culture: {0}", 
                        CultureInfo.CurrentCulture.Name)
      Console.WriteLine("Current Calendar: {0}", 
                        DateTimeFormatInfo.CurrentInfo.Calendar)
   End Sub
End Module
' The example displays the following output:
'    Current Culture: ar-EG
'    Current Calendar: System.Globalization.UmAlQuraCalendar
'    Date: 14/08/32
'    Date in the Invariant Culture: 07/15/2011
'    
'    DateTime.Month property: 7
'    UmAlQura.GetMonth: 8
'    
'    DateTime.Day property: 15
'    UmAlQura.GetDayOfMonth: 14
'    
'    DateTime.Year property: 2011
'    UmAlQura.GetYear: 1432

根據行事曆具現化日期Instantiate dates based on a calendar

由於 DateTimeDateTimeOffset 值是以西曆為主,因此,如果您想要使用不同曆法的日、月或年值,則必須呼叫包含 Calendar 類型之參數的多載建構函式來具現化日期值。Because DateTime and DateTimeOffset values are based on the Gregorian calendar, you must call an overloaded constructor that includes a parameter of type Calendar to instantiate a date value if you want to use the day, month, or year values from a different calendar. 您也可以呼叫特定曆法之 Calendar.ToDateTime 方法的其中一個多載,依據特殊曆法的值具現化 DateTime 物件。You can also call one of the overloads of a specific calendar's Calendar.ToDateTime method to instantiate a DateTime object based on the values of a particular calendar.

下列範例會藉由將 DateTime 物件傳遞至 HebrewCalendar 建構函式具現化一個 DateTime 值,並且藉由呼叫 DateTime 方法具現化另一個 HebrewCalendar.ToDateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Int32) 值。The following example instantiates one DateTime value by passing a HebrewCalendar object to a DateTime constructor, and instantiates a second DateTime value by calling the HebrewCalendar.ToDateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Int32) method. 由於這兩個值是使用希伯來曆法的相同值所建立,因此呼叫 DateTime.Equals 方法會顯示這兩個 DateTime 值相等。Because the two values are created with identical values from the Hebrew calendar, the call to the DateTime.Equals method shows that the two DateTime values are equal.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      HebrewCalendar hc = new HebrewCalendar();

      DateTime date1 = new DateTime(5771, 6, 1, hc);
      DateTime date2 = hc.ToDateTime(5771, 6, 1, 0, 0, 0, 0);
      
      Console.WriteLine("{0:d} (Gregorian) = {1:d2}/{2:d2}/{3:d4} ({4}): {5}",
                        date1, 
                        hc.GetMonth(date2),
                        hc.GetDayOfMonth(date2),
                        hc.GetYear(date2), 
                        GetCalendarName(hc),
                        date1.Equals(date2));
   }
   
   private static string GetCalendarName(Calendar cal)
   {
      return cal.ToString().Replace("System.Globalization.", ""). 
                            Replace("Calendar", "");
   }
}
// The example displays the following output:
//    2/5/2011 (Gregorian) = 06/01/5771 (Hebrew): True
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim hc As New HebrewCalendar()

      Dim date1 As New Date(5771, 6, 1, hc)
      Dim date2 As Date = hc.ToDateTime(5771, 6, 1, 0, 0, 0, 0)
      
      Console.WriteLine("{0:d} (Gregorian) = {1:d2}/{2:d2}/{3:d4} ({4}): {5}",
                        date1, 
                        hc.GetMonth(date2),
                        hc.GetDayOfMonth(date2),
                        hc.GetYear(date2), 
                        GetCalendarName(hc),
                        date1.Equals(date2))
   End Sub
   
   Private Function GetCalendarName(cal As Calendar) As String
      Return cal.ToString().Replace("System.Globalization.", ""). 
                            Replace("Calendar", "")
   End Function
End Module
' The example displays the following output:
'   2/5/2011 (Gregorian) = 06/01/5771 (Hebrew): True

代表目前行事曆中的日期Represent dates in the current calendar

日期和時間格式化方法會固定使用現行曆法將日期轉換為字串。Date and time formatting methods always use the current calendar when converting dates to strings. 這表示年、月和月份日期的字串表示會反映現行曆法,而且不一定會反映西曆。This means that the string representation of the year, the month, and the day of the month reflect the current calendar, and do not necessarily reflect the Gregorian calendar.

下列範例顯示現行曆法如何影響日期的字串表示。The following example shows how the current calendar affects the string representation of a date. 它會將目前文化特性變更為中文 (繁體,台灣),並且具現化日期值。It changes the current culture to Chinese (Traditional, Taiwan), and instantiates a date value. 接著會顯示現行曆法和日期,將現行曆法變更為 TaiwanCalendar,然後再次顯示現行曆法和日期。It then displays the current calendar and the date, changes the current calendar to TaiwanCalendar, and displays the current calendar and date once again. 第一次顯示日期時,該日期會以西曆日期表示。The first time the date is displayed, it is represented as a date in the Gregorian calendar. 第二次顯示日期時,該日期會以台灣曆法的日期表示。The second time it is displayed, it is represented as a date in the Taiwan calendar.

using System;
using System.Globalization;
using System.Threading;

public class Example
{
   public static void Main()
   {
      // Change the current culture to zh-TW.
      CultureInfo zhTW = CultureInfo.CreateSpecificCulture("zh-TW");
      Thread.CurrentThread.CurrentCulture = zhTW;
      // Define a date.
      DateTime date1 = new DateTime(2011, 1, 16);
      
      // Display the date using the default (Gregorian) calendar.
      Console.WriteLine("Current calendar: {0}", 
                        zhTW.DateTimeFormat.Calendar);
      Console.WriteLine(date1.ToString("d"));
      
      // Change the current calendar and display the date.
      zhTW.DateTimeFormat.Calendar = new TaiwanCalendar();      
      Console.WriteLine("Current calendar: {0}", 
                        zhTW.DateTimeFormat.Calendar);
      Console.WriteLine(date1.ToString("d"));
   }
}
// The example displays the following output:
//    Current calendar: System.Globalization.GregorianCalendar
//    2011/1/16
//    Current calendar: System.Globalization.TaiwanCalendar
//    100/1/16
Imports System.Globalization
Imports System.Threading

Module Example
   Public Sub Main()
      ' Change the current culture to zh-TW.
      Dim zhTW As CultureInfo = CultureInfo.CreateSpecificCulture("zh-TW")
      Thread.CurrentThread.CurrentCulture = zhTW
      ' Define a date.
      Dim date1 As Date = #1/16/2011#
      
      ' Display the date using the default (Gregorian) calendar.
      Console.WriteLine("Current calendar: {0}", 
                        zhTW.DateTimeFormat.Calendar)
      Console.WriteLine(date1.ToString("d"))
      
      ' Change the current calendar and display the date.
      zhTW.DateTimeFormat.Calendar = New TaiwanCalendar()      
      Console.WriteLine("Current calendar: {0}", 
                        zhTW.DateTimeFormat.Calendar)
      Console.WriteLine(date1.ToString("d"))
   End Sub
End Module
' The example displays the following output:
'    Current calendar: System.Globalization.GregorianCalendar
'    2011/1/16
'    Current calendar: System.Globalization.TaiwanCalendar
'    100/1/16

代表非目前行事曆中的日期Represent dates in a non-current calendar

若要使用不是特定文化特性的現行曆法來表示日期,您必須呼叫該 Calendar 物件的方法。To represent a date using a calendar that is not the current calendar of a particular culture, you must call methods of that Calendar object. 例如,Calendar.GetYearCalendar.GetMonthCalendar.GetDayOfMonth 方法會將年、月和日轉換成反映特定曆法的值。For example, the Calendar.GetYear, Calendar.GetMonth, and Calendar.GetDayOfMonth methods convert the year, month, and day to values that reflect a particular calendar.

警告

由於某些曆法並非任何文化特性的選擇性曆法,因此使用這些曆法表示日期一定要呼叫曆法方法。Because some calendars are not optional calendars of any culture, representing dates in these calendars always requires that you call calendar methods. 所有衍生自 EastAsianLunisolarCalendarJulianCalendarPersianCalendar 類別的曆法都要這樣做。This is true of all calendars that derive from the EastAsianLunisolarCalendar, JulianCalendar, and PersianCalendar classes.

下列範例使用 JulianCalendar 物件具現化凱撒曆法的日期 1905 年 1 月 9 日。The following example uses a JulianCalendar object to instantiate a date, January 9, 1905, in the Julian calendar. 使用預設曆法 (西曆) 顯示這個日期時,該日期會表示為 1905 年 1 月 22 日。When this date is displayed using the default (Gregorian) calendar, it is represented as January 22, 1905. 呼叫個別 JulianCalendar 方法即可使用凱撒曆法表示日期。Calls to individual JulianCalendar methods enable the date to be represented in the Julian calendar.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      JulianCalendar julian = new JulianCalendar();
      DateTime date1 = new DateTime(1905, 1, 9, julian);
      
      Console.WriteLine("Date ({0}): {1:d}", 
                        CultureInfo.CurrentCulture.Calendar,
                        date1);
      Console.WriteLine("Date in Julian calendar: {0:d2}/{1:d2}/{2:d4}",
                        julian.GetMonth(date1),
                        julian.GetDayOfMonth(date1),
                        julian.GetYear(date1));
   }
}
// The example displays the following output:
//    Date (System.Globalization.GregorianCalendar): 1/22/1905
//    Date in Julian calendar: 01/09/1905
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim julian As New JulianCalendar()
      Dim date1 As New Date(1905, 1, 9, julian)
      
      Console.WriteLine("Date ({0}): {1:d}", 
                        CultureInfo.CurrentCulture.Calendar,
                        date1)
      Console.WriteLine("Date in Julian calendar: {0:d2}/{1:d2}/{2:d4}",
                        julian.GetMonth(date1),
                        julian.GetDayOfMonth(date1),
                        julian.GetYear(date1))
   End Sub
End Module
' The example displays the following output:
'    Date (System.Globalization.GregorianCalendar): 1/22/1905
'    Date in Julian calendar: 01/09/1905

行事曆和日期範圍Calendars and date ranges

曆法所支援的最早日期是由該曆法的 Calendar.MinSupportedDateTime 屬性所表示。The earliest date supported by a calendar is indicated by that calendar's Calendar.MinSupportedDateTime property. 如果是 GregorianCalendar 類別,該日期是公元 0001 年 1 月 1 日。For the GregorianCalendar class, that date is January 1, 0001 C.E. .NET 中的大部分其他行事曆都支援較晚的日期。Most of the other calendars in .NET support a later date. 嘗試處理早於曆法所支援最早日期的日期和時間值,會擲回 ArgumentOutOfRangeException 例外狀況。Trying to work with a date and time value that precedes a calendar's earliest supported date throws an ArgumentOutOfRangeException exception.

不過,有一個重要的例外狀況。However, there is one important exception. DateTime 物件和 DateTimeOffset 物件的預設值 (未初始化的值) 相當於 GregorianCalendar.MinSupportedDateTime 值。The default (uninitialized) value of a DateTime object and a DateTimeOffset object is equal to the GregorianCalendar.MinSupportedDateTime value. 如果您嘗試在不支援西元0001年1月1日的行事曆中格式化此日期If you try to format this date in a calendar that does not support January 1, 0001 C.E. 您不提供格式規範,格式方法會使用 "s" (可排序日期/時間模式)格式規範,而不是 "G" (一般日期/時間模式)格式規範。and you do not provide a format specifier, the formatting method uses the "s" (sortable date/time pattern) format specifier instead of the "G" (general date/time pattern) format specifier. 結果,格式化作業並不會擲回 ArgumentOutOfRangeException 例外狀況,As a result, the formatting operation does not throw an ArgumentOutOfRangeException exception. 而是傳回不支援的日期。Instead, it returns the unsupported date. 下列範例將說明這種情況,當目前文化特性設為日文 (日本) 並採用日本曆法,以及設為阿拉伯文 (埃及) 並採用 Um Al Qura 曆法時,會顯示 DateTime.MinValue 值。This is illustrated in the following example, which displays the value of DateTime.MinValue when the current culture is set to Japanese (Japan) with the Japanese calendar, and to Arabic (Egypt) with the Um Al Qura calendar. 另外也會將目前文化特性設為英文 (美國),並且對每一個 DateTime.ToString(IFormatProvider) 物件呼叫 CultureInfo 方法。It also sets the current culture to English (United States) and calls the DateTime.ToString(IFormatProvider) method with each of these CultureInfo objects. 在每個案例中,日期是使用可排序日期/時間模式顯示。In each case, the date is displayed by using the sortable date/time pattern.

using System;
using System.Globalization;
using System.Threading;

public class Example
{
   public static void Main()
   {
      DateTime dat = DateTime.MinValue;
   
      // Change the current culture to ja-JP with the Japanese Calendar.
      CultureInfo jaJP = CultureInfo.CreateSpecificCulture("ja-JP");
      jaJP.DateTimeFormat.Calendar = new JapaneseCalendar();
      Thread.CurrentThread.CurrentCulture = jaJP;
      Console.WriteLine("Earliest supported date by {1} calendar: {0:d}", 
                        jaJP.DateTimeFormat.Calendar.MinSupportedDateTime,
                        GetCalendarName(jaJP));
      // Attempt to display the date.
      Console.WriteLine(dat.ToString());     
      Console.WriteLine();
      
      // Change the current culture to ar-EG with the Um Al Qura calendar.
      CultureInfo arEG = CultureInfo.CreateSpecificCulture("ar-EG");
      arEG.DateTimeFormat.Calendar = new UmAlQuraCalendar();
      Thread.CurrentThread.CurrentCulture = arEG;
      Console.WriteLine("Earliest supported date by {1} calendar: {0:d}", 
                        arEG.DateTimeFormat.Calendar.MinSupportedDateTime,
                        GetCalendarName(arEG));
      // Attempt to display the date.
      Console.WriteLine(dat.ToString());     
      Console.WriteLine();
      
      // Change the current culture to en-US.
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
      Console.WriteLine(dat.ToString(jaJP));
      Console.WriteLine(dat.ToString(arEG));
      Console.WriteLine(dat.ToString("d"));
   }
   
   private static string GetCalendarName(CultureInfo culture)
   {
      Calendar cal = culture.DateTimeFormat.Calendar;
      return cal.GetType().Name.Replace("System.Globalization.", "").Replace("Calendar", "");  
   }
}
// The example displays the following output:
//       Earliest supported date by Japanese calendar: 明治 1/9/8
//       0001-01-01T00:00:00
//       
//       Earliest supported date by UmAlQura calendar: 01/01/18
//       0001-01-01T00:00:00
//       
//       0001-01-01T00:00:00
//       0001-01-01T00:00:00
//       1/1/0001
Imports System.Globalization
Imports System.Threading

Module Example
   Public Sub Main()
      Dim dat As Date = DateTime.MinValue
   
      ' Change the current culture to ja-JP with the Japanese Calendar.
      Dim jaJP As CultureInfo = CultureInfo.CreateSpecificCulture("ja-JP")
      jaJP.DateTimeFormat.Calendar = New JapaneseCalendar()
      Thread.CurrentThread.CurrentCulture = jaJP
      Console.WriteLine("Earliest supported date by {1} calendar: {0:d}", 
                        jaJP.DateTimeFormat.Calendar.MinSupportedDateTime,
                        GetCalendarName(jaJP))
      ' Attempt to display the date.
      Console.WriteLine(dat.ToString())     
      Console.WriteLine()
      
      ' Change the current culture to ar-EG with the Um Al Qura calendar.
      Dim arEG As CultureInfo = CultureInfo.CreateSpecificCulture("ar-EG")
      arEG.DateTimeFormat.Calendar = New UmAlQuraCalendar()
      Thread.CurrentThread.CurrentCulture = arEG
      Console.WriteLine("Earliest supported date by {1} calendar: {0:d}", 
                        arEG.DateTimeFormat.Calendar.MinSupportedDateTime,
                        GetCalendarName(arEG))
      ' Attempt to display the date.
      Console.WRiteLine(dat.ToString())     
      Console.WRiteLine()
      
      ' Change the current culture to en-US.
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US")
      Console.WriteLine(dat.ToString(jaJP))
      Console.WriteLine(dat.ToString(arEG))
      Console.WriteLine(dat.ToString("d"))
   End Sub
   
   Private Function GetCalendarName(culture As CultureInfo) As String
      Dim cal As Calendar = culture.DateTimeFormat.Calendar
      Return cal.GetType().Name.Replace("System.Globalization.", "").Replace("Calendar", "")  
   End Function
End Module
' The example displays the following output:
'       Earliest supported date by Japanese calendar: 明治 1/9/8
'       0001-01-01T00:00:00
'       
'       Earliest supported date by UmAlQura calendar: 01/01/18
'       0001-01-01T00:00:00
'       
'       0001-01-01T00:00:00
'       0001-01-01T00:00:00
'       1/1/0001

使用紀元Work with eras

曆法通常會將日期細分成紀元。Calendars typically divide dates into eras. 不過,.NET 中的 Calendar 類別並不支援行事曆所定義的每個紀元,而且大部分的 Calendar 類別僅支援單一紀元。However, the Calendar classes in .NET do not support every era defined by a calendar, and most of the Calendar classes support only a single era. 只有 JapaneseCalendarJapaneseLunisolarCalendar 類別支援多個紀元。Only the JapaneseCalendar and JapaneseLunisolarCalendar classes support multiple eras.

重要

Reiwa 時代是 JapaneseCalendarJapaneseLunisolarCalendar的新時代,從 2019 5 月1日開始。The Reiwa era, a new era in the JapaneseCalendar and JapaneseLunisolarCalendar, begins on May 1, 2019. 這項改變對所有使用這些日曆的應用程式都有影響。This change affects all applications that use these calendars. 如需詳細資訊,請參閱下列文章:See the following articles for more information:

大部分行事曆中的紀元代表非常長的時間週期。An era in most calendars denotes an extremely long time period. 例如,在西曆中,目前的紀元橫跨兩個以上的千年來。In the Gregorian calendar, for example, the current era spans more than two millennia. 對於 JapaneseCalendarJapaneseLunisolarCalendar,支援多個紀元的兩個行事曆不是如此。For the JapaneseCalendar and the JapaneseLunisolarCalendar, the two calendars that support multiple eras, this is not the case. 紀元會對應至天皇的統治期間。An era corresponds to the period of an emperor's reign. 支援多個紀元,特別是當目前紀元的上限不明時,會造成特殊挑戰。Support for multiple eras, particularly when the upper limit of the current era is unknown, poses special challenges.

紀元和紀元名稱Eras and era names

在 .NET 中,代表特定行事曆實支援之紀元的整數會以反向順序儲存在 Calendar.Eras 陣列中。In .NET, integers that represent the eras supported by a particular calendar implementation are stored in reverse order in the Calendar.Eras array. 目前的紀元(也就是最新時間範圍的紀元)位於索引零,而針對支援多個紀元的 Calendar 類別,每個連續的索引都會反映前一個紀元。The current era (which is the era with the latest time range) is at index zero, and for Calendar classes that support multiple eras, each successive index reflects the previous era. 靜態 Calendar.CurrentEra 屬性會定義 Calendar.Eras 陣列中目前紀元的索引,它是一個常數,且其值永遠為零。The static Calendar.CurrentEra property defines the index of the current era in the Calendar.Eras array; it is a constant whose value is always zero. 個別 Calendar 類別也會包含傳回目前紀元值的靜態欄位。Individual Calendar classes also include static fields that return the value of the current era. 下表中列出這些欄位。They are listed in the following table.

曆法類別Calendar class 目前紀元欄位Current era field
ChineseLunisolarCalendar ChineseEra
GregorianCalendar ADEra
HebrewCalendar HebrewEra
HijriCalendar HijriEra
JapaneseLunisolarCalendar JapaneseEra
JulianCalendar JulianEra
KoreanCalendar KoreanEra
KoreanLunisolarCalendar GregorianEra
PersianCalendar PersianEra
ThaiBuddhistCalendar ThaiBuddhistEra
UmAlQuraCalendar UmAlQuraEra

對應特定紀元數的名稱可藉由將紀元數傳遞至 DateTimeFormatInfo.GetEraNameDateTimeFormatInfo.GetAbbreviatedEraName 方法的方式擷取。The name that corresponds to a particular era number can be retrieved by passing the era number to the DateTimeFormatInfo.GetEraName or DateTimeFormatInfo.GetAbbreviatedEraName method. 下列範例會呼叫這些方法來擷取 GregorianCalendar 類別中紀元支援的相關資訊。The following example calls these methods to retrieve information about era support in the GregorianCalendar class. 它會顯示與目前紀元之第二年1月1日對應的西曆日期,以及對應至每個支援的日本日曆紀元之第二年1月1日的西曆日期。It displays the Gregorian calendar date that corresponds to January 1 of the second year of the current era, as well as the Gregorian calendar date that corresponds to January 1 of the second year of each supported Japanese calendar era.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      int year = 2;
      int month = 1;
      int day = 1;
      Calendar cal = new JapaneseCalendar();

      Console.WriteLine("\nDate instantiated without an era:");
      DateTime date1 = new DateTime(year, month, day, 0, 0, 0, 0, cal);
      Console.WriteLine("{0}/{1}/{2} in Japanese Calendar -> {3:d} in Gregorian", 
                        cal.GetMonth(date1), cal.GetDayOfMonth(date1),
                        cal.GetYear(date1), date1);
      
      Console.WriteLine("\nDates instantiated with eras:");
      foreach (int era in cal.Eras) {
         DateTime date2 = cal.ToDateTime(year, month, day, 0, 0, 0, 0, era);
         Console.WriteLine("{0}/{1}/{2} era {3} in Japanese Calendar -> {4:d} in Gregorian", 
                           cal.GetMonth(date2), cal.GetDayOfMonth(date2),
                           cal.GetYear(date2), cal.GetEra(date2), date2);
      }                        
   }
}
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim year As Integer = 2
      Dim month As Integer = 1
      Dim day As Integer = 1
      Dim cal As New JapaneseCalendar()

      Console.WriteLine("Date instantiated without an era:")
      Dim date1 As New Date(year, month, day, 0, 0, 0, 0, cal)
      Console.WriteLine("{0}/{1}/{2} in Japanese Calendar -> {3:d} in Gregorian", 
                        cal.GetMonth(date1), cal.GetDayOfMonth(date1),
                        cal.GetYear(date1), date1)
      Console.WriteLine()
      
      Console.WriteLine("Dates instantiated with eras:")
      For Each era As Integer In cal.Eras
         Dim date2 As Date = cal.ToDateTime(year, month, day, 0, 0, 0, 0, era)
         Console.WriteLine("{0}/{1}/{2} era {3} in Japanese Calendar -> {4:d} in Gregorian", 
                           cal.GetMonth(date2), cal.GetDayOfMonth(date2),
                           cal.GetYear(date2), cal.GetEra(date2), date2)
      Next                        
   End Sub
End Module

此外,"g" 自訂日期和時間格式字串包括曆法的紀元名稱,該名稱為日期和時間的字串表示。In addition, the "g" custom date and time format string includes a calendar's era name in the string representation of a date and time. 如需詳細資訊,請參閱自訂日期和時間格式字串For more information, see Custom date and time format strings.

Instantiatie 具有紀元的日期Instantiatie a date with an era

針對支援多個紀元的兩個 Calendar 類別,包含特定年份、月份和月份日期值的日期可能會是不明確的。For the two Calendar classes that support multiple eras, a date that consists of a particular year, month, and day of the month value can be ambiguous. 例如,JapaneseCalendar 支援的所有紀元都有年份,其數目為1。For example, all eras supported by the JapaneseCalendar have years whose number is 1. 一般而言,如果未指定紀元,日期和時間及曆法方法都會假設這些值屬於目前紀元。Ordinarily, if an era is not specified, both date and time and calendar methods assume that values belong to the current era. 這適用于 DateTimeDateTimeOffset 的函式,其中包含 Calendar類型的參數,以及JapaneseCalendar. ToDateTimeJapaneseLunisolarCalendar. ToDateTime方法。This is true of the DateTime and DateTimeOffset constructors that include parameters of type Calendar, as well as the JapaneseCalendar.ToDateTime and JapaneseLunisolarCalendar.ToDateTime methods. 下列範例會具現化代表未指定紀元之第二年1月1日的日期。The following example instantiates a date that represents January 1 of the second year of an unspecified era. 如果您在 Reiwa 紀元為目前紀元時執行此範例,則會將日期解釋為 Reiwa 紀元的第二年。If you execute the example when the Reiwa era is the current era, the date is interpreted as the second year of the Reiwa era. 紀元(令和)會在 DateTime.ToString(String, IFormatProvider) 方法所傳回之字串中的年份之前,並對應至西曆的2020年1月1日。The era, 令和, precedes the year in the string returned by the DateTime.ToString(String, IFormatProvider) method and corresponds to January 1, 2020, in the Gregorian calendar. (Reiwa 紀元會從西曆2019年開始)。(The Reiwa era begins in the year 2019 of the Gregorian calendar.)

using System;
using System.Globalization;

public class Example
{
    public static void Main()
    {
        var japaneseCal = new JapaneseCalendar();
        var jaJp = new CultureInfo("ja-JP");
        jaJp.DateTimeFormat.Calendar = japaneseCal;

        var date = new DateTime(2, 1, 1, japaneseCal);
        Console.WriteLine($"Gregorian calendar date: {date:d}");
        Console.WriteLine($"Japanese calendar date: {date.ToString("d", jaJp)}");
    }
}
Imports System.Globalization

Public Module Example
    Public Sub Main()
        Dim japaneseCal = New JapaneseCalendar()
        Dim jaJp = New CultureInfo("ja-JP")
        jaJp.DateTimeFormat.Calendar = japaneseCal

        Dim dat = New DateTime(2, 1, 1, japaneseCal)
        Console.WriteLine($"Gregorian calendar dat: {dat:d}")
        Console.WriteLine($"Japanese calendar dat: {dat.ToString("d", jaJp)}")
    End Sub
End Module

不過,如果紀元變更,此程式碼的目的就會變得不明確。However, if the era changes, the intent of this code becomes ambiguous. 這是用來代表目前紀元之第二年的日期,還是想要代表 Heisei 紀元的第二年?Is the date intended to represent the second year of the current era, or is it intended to represent the second year of the Heisei era? 有兩種方式可避免這種不明確的情況:There are two ways to avoid this ambiguity:

  • 使用預設 GregorianCalendar 類別來具現化日期和時間值。Instantiate the date and time value using the default GregorianCalendar class. 接著,您可以使用日文行事曆或日文陰陽曆來表示日期的字串,如下列範例所示。You can then use the Japanese calendar or the Japanese Lunisolar calendar for the string representation of dates, as the following example shows.

    using System;
    using System.Globalization;
    
    public class Example
    {
        public static void Main()
        {
            var japaneseCal = new JapaneseCalendar();
            var jaJp = new CultureInfo("ja-JP");
            jaJp.DateTimeFormat.Calendar = japaneseCal;
      
            var date = new DateTime(1905, 2, 12);
            Console.WriteLine($"Gregorian calendar date: {date:d}");
    
            // Call the ToString(IFormatProvider) method.
            Console.WriteLine($"Japanese calendar date: {date.ToString("d", jaJp)}");
            
            // Use a FormattableString object.
            FormattableString fmt = $"{date:d}";
            Console.WriteLine($"Japanese calendar date: {fmt.ToString(jaJp)}");
    
            // Use the JapaneseCalendar object.
            Console.WriteLine($"Japanese calendar date: {jaJp.DateTimeFormat.GetEraName(japaneseCal.GetEra(date))}" +
                              $"{japaneseCal.GetYear(date)}/{japaneseCal.GetMonth(date)}/{japaneseCal.GetDayOfMonth(date)}");
    
            // Use the current culture.
            CultureInfo.CurrentCulture = jaJp;
            Console.WriteLine($"Japanese calendar date: {date:d}");
        }
    }
    // The example displays the following output:
    //   Gregorian calendar date: 2/12/1905
    //   Japanese calendar date: 明治38/2/12
    //   Japanese calendar date: 明治38/2/12
    //   Japanese calendar date: 明治38/2/12
    //   Japanese calendar date: 明治38/2/12
    
    Imports System.Globalization
    
    Public Module Example
        Public Sub Main()
            Dim japaneseCal = New JapaneseCalendar()
            Dim jaJp = New CultureInfo("ja-JP")
            jaJp.DateTimeFormat.Calendar = japaneseCal
      
            Dim dat = New DateTime(1905, 2, 12)
            Console.WriteLine($"Gregorian calendar date: {dat:d}")
    
            ' Call the ToString(IFormatProvider) method.
            Console.WriteLine($"Japanese calendar date: {dat.ToString("d", jaJp)}")
            
            ' Use a FormattableString object.
            Dim fmt As FormattableString = $"{dat:d}"
            Console.WriteLine($"Japanese calendar date: {fmt.ToString(jaJp)}")
    
            ' Use the JapaneseCalendar object.
            Console.WriteLine($"Japanese calendar date: {jaJp.DateTimeFormat.GetEraName(japaneseCal.GetEra(dat))}" +
                              $"{japaneseCal.GetYear(dat)}/{japaneseCal.GetMonth(dat)}/{japaneseCal.GetDayOfMonth(dat)}")
    
            ' Use the current culture.
            CultureInfo.CurrentCulture = jaJp
            Console.WriteLine($"Japanese calendar date: {dat:d}")
        End Sub
    End Module
    ' The example displays the following output:
    '   Gregorian calendar date: 2/12/1905
    '   Japanese calendar date: 明治38/2/12
    '   Japanese calendar date: 明治38/2/12
    '   Japanese calendar date: 明治38/2/12
    '   Japanese calendar date: 明治38/2/12
    
    
    
  • 呼叫明確指定紀元的日期和時間方法。Call a date and time method that explicitly specifies an era. 這包括下列方法︰This includes the following methods:

    下列範例會使用其中三種方法,將日期和時間(從1868年9月8日開始,在1912年7月29日起結束)的 Meiji 紀元中具現化。The following example uses three of these methods to instantiate a date and time in the Meiji era, which began on September 8, 1868, and ended on July 29, 1912.

    using System;
    using System.Globalization;
    
    public class Example
    {
        public static void Main()
        {
            var japaneseCal = new JapaneseCalendar();
            var jaJp = new CultureInfo("ja-JP");
            jaJp.DateTimeFormat.Calendar = japaneseCal;
      
            // We can get the era index by calling DateTimeFormatInfo.GetEraName.
            int eraIndex = 0;
    
            for (int ctr = 0; ctr < jaJp.DateTimeFormat.Calendar.Eras.Length; ctr++) 
               if (jaJp.DateTimeFormat.GetEraName(ctr) == "明治")
                  eraIndex = ctr; 
            var date1 = japaneseCal.ToDateTime(23, 9, 8, 0, 0, 0, 0, eraIndex);
            Console.WriteLine($"{date1.ToString("d", jaJp)} (Gregorian {date1:d}");
    
            try {
                var date2 = DateTime.Parse("明治23/9/8", jaJp);
                Console.WriteLine($"{date1.ToString("d", jaJp)} (Gregorian {date1:d}");
            }
            catch (FormatException)
            {
                Console.WriteLine("The parsing operation failed.");
            }
    
            try {
                var date3 = DateTime.ParseExact("明治23/9/8", "gyy/m/d", jaJp);
                Console.WriteLine($"{date1.ToString("d", jaJp)} (Gregorian {date1:d}");
            }
            catch (FormatException)
            {
                Console.WriteLine("The parsing operation failed.");
            }
        }
    }
    // The example displays the following output:
    //   明治23/9/8 (Gregorian 9/8/1890
    //   明治23/9/8 (Gregorian 9/8/1890
    //   明治23/9/8 (Gregorian 9/8/1890
    
    Imports System.Globalization
    
    Public Module Example
        Public Sub Main()
            Dim japaneseCal = New JapaneseCalendar()
            Dim jaJp = New CultureInfo("ja-JP")
            jaJp.DateTimeFormat.Calendar = japaneseCal
      
            ' We can get the era index by calling DateTimeFormatInfo.GetEraName.
           Dim eraIndex As Integer = 0
    
            For ctr As Integer = 0 To jaJp.DateTimeFormat.Calendar.Eras.Length - 1 
               If jaJp.DateTimeFormat.GetEraName(ctr) = "明治" Then eraIndex = ctr 
            Next
            Dim date1 = japaneseCal.ToDateTime(23, 9, 8, 0, 0, 0, 0, eraIndex)
            Console.WriteLine($"{date1.ToString("d", jaJp)} (Gregorian {date1:d}")
    
            Try 
                Dim date2 = DateTime.Parse("明治23/9/8", jaJp)
                Console.WriteLine($"{date1.ToString("d", jaJp)} (Gregorian {date1:d}")
            Catch e As FormatException
                Console.WriteLine("The parsing operation failed.")
            End Try
    
            Try 
                Dim date3 = DateTime.ParseExact("明治23/9/8", "gyy/m/d", jaJp)
                Console.WriteLine($"{date1.ToString("d", jaJp)} (Gregorian {date1:d}")
            Catch e As FormatException
                Console.WriteLine("The parsing operation failed.")
            End Try
        End Sub
    End Module
    ' The example displays the following output:
    '   明治23/9/8 (Gregorian 9/8/1890
    '   明治23/9/8 (Gregorian 9/8/1890
    '   明治23/9/8 (Gregorian 9/8/1890
    

提示

當使用支援多個紀元的行事歷時,請一律使用西曆日期來具現化日期,或指定根據該行事曆具現化日期和時間時的紀元。When working with calendars that support multiple eras, always use the Gregorian date to instantiate a date, or specify the era when you instantiate a date and time based on that calendar.

在指定紀元給 ToDateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Int32) 方法時,您會在行事曆的 Eras 屬性中提供紀元的索引。In specifying an era to the ToDateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Int32) method, you provide the index of the era in the calendar's Eras property. 不過,對於其紀元有可能變更的行事曆,這些索引不是常數值;目前的紀元位於索引0,而最舊的紀元位於索引 Eras.Length - 1For calendars whose eras are subject to change, however, these indexes are not constant values; the current era is at index 0, and the oldest era is at index Eras.Length - 1. 當新紀元加入行事歷時,先前紀元的索引會增加一個。When a new era is added to a calendar, the indexes of the previous eras increase by one. 您可以提供適當的紀元索引,如下所示:You can supply the appropriate era index as follows:

行事曆、紀元和日期範圍:寬鬆範圍檢查Calendars, eras, and date ranges: Relaxed range checks

非常類似于個別行事曆支援的日期範圍,JapaneseCalendarJapaneseLunisolarCalendar 類別中的紀元也具有支援的範圍。Very much like individual calendars have supported date ranges, eras in the JapaneseCalendar and JapaneseLunisolarCalendar classes also have supported ranges. 之前,.NET 使用嚴格的紀元範圍檢查,以確保紀元特定日期在該紀元的範圍內。Previously, .NET used strict era range checks to ensure that an era-specific date was within the range of that era. 也就是說,如果日期超出指定紀元的範圍,此方法就會擲回 ArgumentOutOfRangeExceptionThat is, if a date is outside of the range of the specified era, the method throws an ArgumentOutOfRangeException. 目前,.NET 預設會使用寬鬆範圍檢查。Currently, .NET uses relaxed ranged checking by default. 所有 .NET 版本的更新引進了寬鬆的紀元範圍檢查;嘗試將指定的紀元範圍外的紀元特定日期「溢位」到下列紀元,而且不會擲回任何例外狀況。Updates to all versions of .NET introduced relaxed era range checks; the attempt to instantiate an era-specific date that is outside the range of the specified era "overflows" into the following era, and no exception is thrown.

下列範例會嘗試在 Showa 紀元的65th 年份中,將日期具現化,這會在1926年12月25日開始,並于1989年1月7日結束。The following example attempts to instantiate a date in the 65th year of the Showa era, which began on December 25, 1926 and ended on January 7, 1989. 此日期對應于1990年1月9日,這超出 JapaneseCalendar的 Showa 紀元範圍。This date corresponds to January 9, 1990, which is outside the range of the Showa era in the JapaneseCalendar. 如範例的輸出所示,此範例所顯示的日期為1990年1月9日(Heisei 紀元的第二年)。As the output from the example illustrates, the date displayed by the example is January 9, 1990, in the second year of the Heisei era.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      var jaJp = new CultureInfo("ja-JP");
      var cal = new JapaneseCalendar();
      jaJp.DateTimeFormat.Calendar = cal;
      string showaEra = "昭和";

      var dt = cal.ToDateTime(65, 1, 9, 15, 0, 0, 0, GetEraIndex(showaEra));
      FormattableString fmt = $"{dt:d}";

      Console.WriteLine($"Japanese calendar date: {fmt.ToString(jaJp)}");
      Console.WriteLine($"Gregorian calendar date: {fmt}");

      int GetEraIndex(string eraName)
      {
         foreach (var ctr in cal.Eras)
            if (jaJp.DateTimeFormat.GetEraName(ctr) == eraName)
               return ctr;

         return 0; 
      }
   }
}
// The example displays the following output:
//   Japanese calendar date: 平成2/1/9
//   Gregorian calendar date: 1/9/1990
Imports System.Globalization

Public Module Example
   Dim jaJp As CultureInfo
   Dim cal As Calendar

   Public Sub Main()
      jaJp = New CultureInfo("ja-JP")  
      cal = New JapaneseCalendar()
      jaJp.DateTimeFormat.Calendar = cal
      Dim showaEra = "昭和"

      Dim dt = cal.ToDateTime(65, 1, 9, 15, 0, 0, 0, GetEraIndex(showaEra))
      Dim fmt As FormattableString = $"{dt:d}"
      Console.WriteLine($"Japanese calendar date: {fmt.ToString(jaJp)}")
      Console.WriteLine($"Gregorian calendar date: {fmt}")
   End Sub
  
   Private Function GetEraIndex(eraName As String) As Integer
      For Each ctr As Integer In cal.Eras
         If jaJp.DateTimeFormat.GetEraName(ctr) = eraName Then Return ctr
      Next
      Return 0
   End Function
End Module
' The example displays the following output:
'   Japanese calendar date: 平成2/1/9
'   Gregorian calendar date: 1/9/1990

如果不想要寬鬆的範圍檢查,您可以透過數種方式來還原嚴格的範圍檢查,端視應用程式執行所在的 .NET 版本而定:If relaxed range checks are undesirable, you can restore strict range checks in a number of ways, depending on the version of .NET on which your application is running:

  • .Net Core: 將下列內容新增至netcore中的 json 設定檔案:.NET Core: Add the following to the .netcore.runtime.json config file:

    "runtimeOptions": {
      "configProperties": {
          "Switch.System.Globalization.EnforceJapaneseEraYearRanges": true
      }
    }
    
  • .NET Framework 4.6 或更新版本:app.config檔案中設定下列 AppCoNtext 參數:.NET Framework 4.6 or later: Set the following AppContext switch in the app.config file:

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <runtime>
        <AppContextSwitchOverrides value="Switch.System.Globalization.EnforceJapaneseEraYearRanges=true" />
      </runtime>
    </configuration>
    
  • .NET Framework 4.5.2 或更早版本: 設定下列登錄值:.NET Framework 4.5.2 or earlier: Set the following registry value:

    KeyKey HKEY_LOCAL_MACHINE \Software\Microsoft\。NETFramework\AppCoNtextHKEY_LOCAL_MACHINE\Software\Microsoft\.NETFramework\AppContext
    名稱Name EnforceJapaneseEraYearRanges。Switch.System.Globalization.EnforceJapaneseEraYearRanges
    TypeType REG_SZREG_SZ
    Value truetrue

啟用 strict 範圍檢查之後,先前的範例會擲回 ArgumentOutOfRangeException 並顯示下列輸出:With strict range checks enabled, the previous example throws an ArgumentOutOfRangeException and displays the following output:

Unhandled Exception: System.ArgumentOutOfRangeException: Valid values are between 1 and 64, inclusive.
Parameter name: year
   at System.Globalization.GregorianCalendarHelper.GetYearOffset(Int32 year, Int32 era, Boolean throwOnError)
   at System.Globalization.GregorianCalendarHelper.ToDateTime(Int32 year, Int32 month, Int32 day, Int32 hour, Int32 minute, Int32 second, Int32 millisecond, Int32 era)
   at Example.Main()

代表具有多個紀元之行事曆中的日期Represent dates in calendars with multiple eras

如果 Calendar 物件支援紀元而且是 CultureInfo 物件的現行曆法,則紀元會包含在完整日期和時間模式、完整日期模式及簡短日期模式之日期和時間值的字串表示中。If a Calendar object supports eras and is the current calendar of a CultureInfo object, the era is included in the string representation of a date and time value for the full date and time, long date, and short date patterns. 下列範例顯示目前文化特性為日本 (日文) 且現行曆法為日本曆法時的這些日期模式。The following example displays these date patterns when the current culture is Japan (Japanese) and the current calendar is the Japanese calendar.

using System;
using System.Globalization;
using System.IO;
using System.Threading;

public class Example
{
   public static void Main()
   {
      StreamWriter sw = new StreamWriter(@".\eras.txt");
      DateTime dt = new DateTime(2012, 5, 1);
      
      CultureInfo culture = CultureInfo.CreateSpecificCulture("ja-JP");
      DateTimeFormatInfo dtfi = culture.DateTimeFormat;
      dtfi.Calendar = new JapaneseCalendar();
      Thread.CurrentThread.CurrentCulture = culture;
      
      sw.WriteLine("\n{0,-43} {1}", "Full Date and Time Pattern:", dtfi.FullDateTimePattern);
      sw.WriteLine(dt.ToString("F"));
      sw.WriteLine();
      
      sw.WriteLine("\n{0,-43} {1}", "Long Date Pattern:", dtfi.LongDatePattern);
      sw.WriteLine(dt.ToString("D"));
      
      sw.WriteLine("\n{0,-43} {1}", "Short Date Pattern:", dtfi.ShortDatePattern);
      sw.WriteLine(dt.ToString("d"));
      sw.Close();
    }
}
// The example writes the following output to a file:
//    Full Date and Time Pattern:                 gg y'年'M'月'd'日' H:mm:ss
//    平成 24年5月1日 0:00:00
//    
//    Long Date Pattern:                          gg y'年'M'月'd'日'
//    平成 24年5月1日
//    
//    Short Date Pattern:                         gg y/M/d
//    平成 24/5/1
Imports System.Globalization
Imports System.IO
Imports System.Threading

Module Example
   Public Sub Main()
      Dim sw As New StreamWriter(".\eras.txt")
      Dim dt As Date = #05/01/2012#
      
      Dim culture As CultureInfo = CultureInfo.CreateSpecificCulture("ja-JP")
      Dim dtfi As DateTimeFormatInfo = culture.DateTimeFormat
      dtfi.Calendar = New JapaneseCalendar()
      Thread.CurrentThread.CurrentCulture = culture
      
      sw.WriteLine("{0,-43} {1}", "Full Date and Time Pattern:", dtfi.FullDateTimePattern)
      sw.WriteLine(dt.ToString("F"))
      sw.WriteLine()
      
      sw.WriteLine("{0,-43} {1}", "Long Date Pattern:", dtfi.LongDatePattern)
      sw.WriteLine(dt.ToString("D"))
      sw.WriteLine()
      
      sw.WriteLine("{0,-43} {1}", "Short Date Pattern:", dtfi.ShortDatePattern)
      sw.WriteLine(dt.ToString("d"))
      sw.WriteLine()
      sw.Close()
   End Sub
End Module
' The example writes the following output to a file:
'    Full Date and Time Pattern:                 gg y'年'M'月'd'日' H:mm:ss
'    平成 24年5月1日 0:00:00
'    
'    Long Date Pattern:                          gg y'年'M'月'd'日'
'    平成 24年5月1日
'    
'    Short Date Pattern:                         gg y/M/d
'    平成 24/5/1 

警告

JapaneseCalendar 類別是 .NET 中唯一支援多個紀元中的日期,而且可以是 CultureInfo 物件的目前行事曆的月曆類別,特別是代表日文(日本)文化特性的 CultureInfo 物件。The JapaneseCalendar class is the only calendar class in .NET that both supports dates in more than one era and that can be the current calendar of a CultureInfo object - specifically, of a CultureInfo object that represents the Japanese (Japan) culture.

針對所有曆法,"g" 自訂格式規範會在結果字串中包含紀元。For all calendars, the "g" custom format specifier includes the era in the result string. 下列範例在現行曆法為西曆時,使用 "MM-dd-yyyy g" 自訂格式字串在結果字串中包含紀元。The following example uses the "MM-dd-yyyy g" custom format string to include the era in the result string when the current calendar is the Gregorian calendar.

   DateTime dat = new DateTime(2012, 5, 1);
   Console.WriteLine("{0:MM-dd-yyyy g}", dat);
// The example displays the following output:
//     05-01-2012 A.D.      
Dim dat As Date = #05/01/2012#
Console.WriteLine("{0:MM-dd-yyyy g}", dat)
' The example displays the following output:
'     05-01-2012 A.D.      

在日期的字串表示不是以現行曆法表示的情況下,Calendar 類別會包含 Calendar.GetEra 方法,該方法可搭配 Calendar.GetYearCalendar.GetMonthCalendar.GetDayOfMonth 方法用來明確指出日期,以及該日期所屬的紀元。In cases where the string representation of a date is expressed in a calendar that is not the current calendar, the Calendar class includes a Calendar.GetEra method that can be used along with the Calendar.GetYear, Calendar.GetMonth, and Calendar.GetDayOfMonth methods to unambiguously indicate a date as well as the era to which it belongs. 下列範例使用 JapaneseLunisolarCalendar 類別提供圖例。The following example uses the JapaneseLunisolarCalendar class to provide an illustration. 不過請注意,若要在結果字串中包含代表紀元的有意義名稱或縮寫而非整數,必須將 DateTimeFormatInfo 物件具現化,並且讓 JapaneseCalendar 成為現行曆法However, note that including a meaningful name or abbreviation instead of an integer for the era in the result string requires that you instantiate a DateTimeFormatInfo object and make JapaneseCalendar its current calendar. (JapaneseLunisolarCalendar 曆法不得為任何文化特性的現行曆法,但在這個案例中,兩個曆法共用相同的紀元)。(The JapaneseLunisolarCalendar calendar cannot be the current calendar of any culture, but in this case the two calendars share the same eras.)

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      DateTime date1 = new DateTime(2011, 8, 28);
      Calendar cal = new JapaneseLunisolarCalendar();
      
      Console.WriteLine("{0} {1:d4}/{2:d2}/{3:d2}", 
                        cal.GetEra(date1),
                        cal.GetYear(date1),
                        cal.GetMonth(date1),
                        cal.GetDayOfMonth(date1)); 
                        
      // Display eras
      CultureInfo culture = CultureInfo.CreateSpecificCulture("ja-JP");
      DateTimeFormatInfo dtfi = culture.DateTimeFormat;
      dtfi.Calendar = new JapaneseCalendar();
      
      Console.WriteLine("{0} {1:d4}/{2:d2}/{3:d2}", 
                        dtfi.GetAbbreviatedEraName(cal.GetEra(date1)),
                        cal.GetYear(date1),
                        cal.GetMonth(date1),
                        cal.GetDayOfMonth(date1)); 
   }
}
// The example displays the following output:
//       4 0023/07/29
//       平 0023/07/29
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim date1 As Date = #8/28/2011#
      Dim cal As New JapaneseLunisolarCalendar()
      Console.WriteLine("{0} {1:d4}/{2:d2}/{3:d2}", 
                        cal.GetEra(date1),
                        cal.GetYear(date1),
                        cal.GetMonth(date1),
                        cal.GetDayOfMonth(date1)) 
                        
      ' Display eras
      Dim culture As CultureInfo = CultureInfo.CreateSpecificCulture("ja-JP")
      Dim dtfi As DateTimeFormatInfo = culture.DateTimeFormat
      dtfi.Calendar = New JapaneseCalendar()
      
      Console.WriteLine("{0} {1:d4}/{2:d2}/{3:d2}", 
                        dtfi.GetAbbreviatedEraName(cal.GetEra(date1)),
                        cal.GetYear(date1),
                        cal.GetMonth(date1),
                        cal.GetDayOfMonth(date1)) 
   End Sub
End Module
' The example displays the following output:
'       4 0023/07/29
'       平 0023/07/29

在日文行事曆中,紀元的第一年稱為 Gannen (元年)。In the Japanese calendars, the first year of an era is called Gannen (元年). 例如,Heisei 紀元的第一年可以描述為 Heisei Gannen,而不是 Heisei 1。For example, instead of Heisei 1, the first year of the Heisei era can be described as Heisei Gannen. CultureInfo 使用下列標準或自訂日期和時間格式字串來搭配使用 JapaneseCalendar 類別的日本-日本("ja-jp")文化特性時,.NET 會採用這種慣例來格式化日期和時間的格式作業:.NET adopts this convention in formatting operations for dates and times formatted with the following standard or custom date and time format strings when they are used with a CultureInfo object that represents the Japanese-Japan ("ja-JP") culture with the JapaneseCalendar class:

例如,下列範例會在 JapaneseCalendar中顯示 Heisei 紀元的第一年的日期。For example, the following example displays a date in the first year of the Heisei era in the JapaneseCalendar.

using System;
using System.Globalization;

public class Example
{
    public static void Main()
    {
         var enUs = new CultureInfo("en-US");
        var japaneseCal = new JapaneseCalendar();
        var jaJp = new CultureInfo("ja-JP");
        jaJp.DateTimeFormat.Calendar = japaneseCal;
        string heiseiEra = "平成";

        var date = japaneseCal.ToDateTime(1, 8, 18, 0, 0, 0, 0, GetEraIndex(heiseiEra));
        FormattableString fmt = $"{date:D}";
        Console.WriteLine($"Japanese calendar date: {fmt.ToString(jaJp)} (Gregorian: {fmt.ToString(enUs)})");

        int GetEraIndex(string eraName)
        {
           foreach (var ctr in japaneseCal.Eras)
              if (jaJp.DateTimeFormat.GetEraName(ctr) == eraName)
                 return ctr;

           return 0; 
        }
    }
}
// The example displays the following output:
//    Japanese calendar date: 平成元年8月18日 (Gregorian: Friday, August 18, 1989)
Imports System.Globalization

Module Program
    Dim jaJp As CultureInfo
    Dim japaneseCal As Calendar

    Sub Main()
        Dim enUs = New CultureInfo("en-US")
        japaneseCal = New JapaneseCalendar()
        jaJp = New CultureInfo("ja-JP")
        jaJp.DateTimeFormat.Calendar = japaneseCal
        Dim heiseiEra = "平成"

        Dim dat = japaneseCal.ToDateTime(1, 8, 18, 0, 0, 0, 0, GetEraIndex(heiseiEra))
        Dim fmt As FormattableString = $"{dat:D}"
        Console.WriteLine($"Japanese calendar date: {fmt.ToString(jaJp)} (Gregorian: {fmt.ToString(enUs)})")
    End Sub

    Private Function GetEraIndex(eraName As String) As Integer
        For Each ctr In japaneseCal.Eras
            If jaJp.DateTimeFormat.GetEraName(ctr) = eraName Then
                Return ctr
            End If
        Next
        Return 0 
    End Function
End Module
' The example displays the following output:
'    Japanese calendar date: 平成元年8月18日 (Gregorian: Friday, August 18, 1989)

如果在格式化作業中不需要此行為,您可以執行下列動作來還原先前的行為,這一律會將紀元的第一年表示為 "1" 而不是 "Gannen",視 .NET 的版本而定:If this behavior is undesirable in formatting operations, you can restore the previous behavior, which always represents the first year of an era as "1" rather than "Gannen", by doing the following, depending on the version of .NET:

  • .Net Core: 將下列內容新增至netcore中的 json 設定檔案:.NET Core: Add the following to the .netcore.runtime.json config file:

    "runtimeOptions": {
      "configProperties": {
          "Switch.System.Globalization.FormatJapaneseFirstYearAsANumber": true
      }
    }
    
  • .NET Framework 4.6 或更新版本:app.config檔案中設定下列 AppCoNtext 參數:.NET Framework 4.6 or later: Set the following AppContext switch in the app.config file:

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <runtime>
        <AppContextSwitchOverrides value="Switch.System.Globalization.FormatJapaneseFirstYearAsANumber=true" />
      </runtime>
    </configuration>
    
  • .NET Framework 4.5.2 或更早版本: 設定下列登錄值:.NET Framework 4.5.2 or earlier: Set the following registry value:

    KeyKey HKEY_LOCAL_MACHINE \Software\Microsoft\。NETFramework\AppCoNtextHKEY_LOCAL_MACHINE\Software\Microsoft\.NETFramework\AppContext
    名稱Name FormatJapaneseFirstYearAsANumber。Switch.System.Globalization.FormatJapaneseFirstYearAsANumber
    TypeType REG_SZREG_SZ
    Value truetrue

在停用格式化作業的 gannen 支援之後,上一個範例會顯示下列輸出:With gannen support in formatting operations disabled, the previous example displays the following output:

Japanese calendar date: 平成1年8月18日 (Gregorian: Friday, August 18, 1989)

.NET 也已更新,讓日期和時間剖析作業支援包含年份表示為 "1" 或 Gannen 的字串。.NET has also been updated so that date and time parsing operations support strings that contain the year represented as either "1" or Gannen. 雖然您應該不需要這麼做,但您可以還原先前的行為,只將 "1" 視為紀元的第一年。Although you should not need to do this, you can restore the previous behavior to recognizes only "1" as the first year of an era. 視 .NET 版本而定,您可以如下所示執行此動作:You can do this as follows, depending on the version of .NET:

  • .Net Core: 將下列內容新增至netcore中的 json 設定檔案:.NET Core: Add the following to the .netcore.runtime.json config file:

    "runtimeOptions": {
      "configProperties": {
          "Switch.System.Globalization.EnforceLegacyJapaneseDateParsing": true
      }
    }
    
  • .NET Framework 4.6 或更新版本:app.config檔案中設定下列 AppCoNtext 參數:.NET Framework 4.6 or later: Set the following AppContext switch in the app.config file:

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <runtime>
        <AppContextSwitchOverrides value="Switch.System.Globalization.EnforceLegacyJapaneseDateParsing=true" />
      </runtime>
    </configuration>
    
  • .NET Framework 4.5.2 或更早版本: 設定下列登錄值:.NET Framework 4.5.2 or earlier: Set the following registry value:

    KeyKey HKEY_LOCAL_MACHINE \Software\Microsoft\。NETFramework\AppCoNtextHKEY_LOCAL_MACHINE\Software\Microsoft\.NETFramework\AppContext
    名稱Name EnforceLegacyJapaneseDateParsing。Switch.System.Globalization.EnforceLegacyJapaneseDateParsing
    TypeType REG_SZREG_SZ
    Value truetrue

請參閱See also