使用日历Working 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 中的日历的支持,并讨论了使用日期值时的 calendar 类的使用。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.

请注意,以下六个日历类只能用作独立日历:ChineseLunisolarCalendarJapaneseLunisolarCalendarJulianCalendarKoreanLunisolarCalendarPersianCalendarTaiwanLunisolarCalendarNote 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). 接下来,该示例将当前区域性更改为阿拉伯语(沙特阿拉伯),并使用其默认的古兰经历显示该日期。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. 在此示例中,当前区域性为阿拉伯语(埃及),当前日历为古兰经历。In the example, the current culture is Arabic (Egypt), and the current calendar is Um Al Qura. DateTime 值设置为 2011 年 7 月 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,与古兰经历中的日期等效。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 成员返回的值反映古兰经历中的值。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

基于日历实例化日期Instantiating 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

表示当前日历中的日期Representing 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

表示非当前日历中的日期Representing 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. 下面的示例阐释了这一点,在使用日语日历将当前区域性设置为日语(日本)以及使用古兰经历将当前区域性设置为阿拉伯语(埃及)时,它将显示 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

使用纪元Working 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中的新纪元于5月1日(2019)开始。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. 例如,在公历中,当前纪元跨越两个以上的 millennia。In the Gregorian calendar, for example, the current era spans more than two millennia. JapaneseCalendar 对于JapaneseLunisolarCalendar和,两个支持多个纪元的日历不是这样。For the JapaneseCalendar and the JapaneseLunisolarCalendar, the two calendars that support multiple eras, this is not the case. 纪元对应于高层的 reign 的时间段。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.

使用纪元实例化日期Instantiating 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. 这适用于包含Calendar类型参数的DateTimeDateTimeOffset构造函数, 以及 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:

    下面的示例使用三种方法来实例化 Meiji 纪元中的日期和时间,该日期和时间从1868年9月8日开始,结束于1912年7月29日结束。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 - 1处。For 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. 将新纪元添加到日历时,先前纪元的索引将增加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日,超过了 Showa 时代JapaneseCalendar的范围。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配置文件:.NET Core: You can add the following to the .netcore.runtime.json config file:

    "runtimeOptions": {
      "configProperties": {
          "Switch.System.Globalization.EnforceJapaneseEraYearRanges": true
      }
    }
    
  • .NET Framework 4.6 或更高版本: 可以设置以下 AppContext 开关:.NET Framework 4.6 or later: You can set the following AppContext switch:

    <?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: You can set the following registry value:

    KeyKey HKEY_LOCAL_MACHINE\Software\Microsoft.NETFramework\AppContextHKEY_LOCAL_MACHINE\Software\Microsoft.NETFramework\AppContext
    nameName Switch.System.Globalization.EnforceJapaneseEraYearRangesSwitch.System.Globalization.EnforceJapaneseEraYearRanges
    类型Type REG_SZREG_SZ
    Value truetrue

启用严格范围检查后,上面的示例将引发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()

用多个纪元表示日历中的日期Representing 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 

警告

类是 .net 中唯一支持多个纪元中的日期并且可以是CultureInfo对象的当前日历(具体而言,是表示日语(日本)区域性的CultureInfo对象)的 calendar 类。 JapaneseCalendarThe 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.GetEraCalendar.GetYearCalendar.GetMonth 方法一起使用的 Calendar.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 1,而是 Heisei Gannen。For example, instead of Heisei 1, the first year of the Heisei era can be described as Heisei Gannen. 当使用以下标准或自定义日期和时间格式字符串与CultureInfo表示日语-日本("ja-jp")区域性的对象使用时,.net采用这种格式设置操作的格式JapaneseCalendar类:.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:

例如,下面的示例在的 Heisei 时代JapaneseCalendar的第一年显示日期。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配置文件:.NET Core: You can add the following to the .netcore.runtime.json config file:

    "runtimeOptions": {
      "configProperties": {
          "Switch.System.Globalization.FormatJapaneseFirstYearAsANumber": true
      }
    }
    
  • .NET Framework 4.6 或更高版本: 可以设置以下 AppContext 开关:.NET Framework 4.6 or later: You can set the following AppContext switch:

    <?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: You can set the following registry value:

    KeyKey HKEY_LOCAL_MACHINE\Software\Microsoft.NETFramework\AppContextHKEY_LOCAL_MACHINE\Software\Microsoft.NETFramework\AppContext
    名称Name Switch.System.Globalization.FormatJapaneseFirstYearAsANumberSwitch.System.Globalization.FormatJapaneseFirstYearAsANumber
    类型Type 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配置文件:.NET Core: You can add the following to the .netcore.runtime.json config file:

    "runtimeOptions": {
      "configProperties": {
          "Switch.System.Globalization.EnforceLegacyJapaneseDateParsing": true
      }
    }
    
  • .NET Framework 4.6 或更高版本: 可以设置以下 AppContext 开关:.NET Framework 4.6 or later: You can set the following AppContext switch:

    <?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: You can set the following registry value:

    KeyKey HKEY_LOCAL_MACHINE\Software\Microsoft.NETFramework\AppContextHKEY_LOCAL_MACHINE\Software\Microsoft.NETFramework\AppContext
    nameName Switch.System.Globalization.EnforceLegacyJapaneseDateParsingSwitch.System.Globalization.EnforceLegacyJapaneseDateParsing
    类型Type REG_SZREG_SZ
    Value truetrue

请参阅See also