Export (0) Print
Expand All
This topic has not yet been rated - Rate this topic

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. This topic explores the support for calendars in the .NET Framework and discusses the use of the calendar classes when working with date values.

All calendars in the .NET Framework derive from the System.Globalization.Calendar class, which provides the base calendar implementation. One of the classes that inherits from the Calendar class is the EastAsianLunisolarCalendar class, which is the base class for all lunisolar calendars. The .NET Framework includes the following calendar implementations:

A calendar can be used in one of two ways:

  • As the calendar used by a specific culture. 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 objects also have optional calendars, which include additional calendars that that culture can use.

  • As a standalone calendar independent of a specific culture. In this case, Calendar methods are used to express dates as values that reflect the calendar.

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.

Each culture has a default calendar, which is defined by the CultureInfo.Calendar property. 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.

The following example illustrates the CultureInfo.Calendar and CultureInfo.OptionalCalendars properties. It creates CultureInfo objects for the Thai (Thailand) and Japanese (Japan) cultures and displays their default and optional calendars. 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)

The calendar currently in use by a particular CultureInfo object is defined by the culture's DateTimeFormatInfo.Calendar property. A culture's DateTimeFormatInfo object is returned by the CultureInfo.DateTimeFormat property. When a culture is created, its default value is the same as the value of the CultureInfo.Calendar property. However, you can change the culture's current calendar to any calendar contained in the array returned by the CultureInfo.OptionalCalendars property. If 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. 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. 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

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. 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.

Important note Important

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.

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. A DateTime value is set to the fifteenth day of the seventh month of 2011. 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. 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. Next, members of DateTime and Calendar are used to return the day, the month, and the year of the DateTime value. 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

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. 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.

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. 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

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. 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

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. For example, the Calendar.GetYear, Calendar.GetMonth, and Calendar.GetDayOfMonth methods convert the year, month, and day to values that reflect a particular calendar.

Caution note Caution

Because some calendars are not optional calendars of any culture, representing dates in these calendars always requires that you call calendar methods. This is true of all calendars that derive from the EastAsianLunisolarCalendar, JulianCalendar, and PersianCalendar classes.

The following example uses a JulianCalendar object to instantiate a date, January 9, 1905, in the Julian calendar. When this date is displayed using the default (Gregorian) calendar, it is represented as January 22, 1905. 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

The earliest date supported by a calendar is indicated by that calendar's Calendar.MinSupportedDateTime property. For the GregorianCalendar class, that date is January 1, 0001 C.E. Most of the other calendars in the .NET Framework support a later date. 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. The default (uninitialized) value of a DateTime object and a DateTimeOffset object is equal to the GregorianCalendar.MinSupportedDateTime value. If you try to format this date in a calendar that does not support January 1, 0001 C.E. 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. As a result, the formatting operation does not throw an ArgumentOutOfRangeException exception. Instead, it returns the unsupported date. 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. 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

Calendars typically divide dates into eras. However, the Calendar classes in the .NET Framework do not support every era defined by a calendar, and most of the Calendar classes support only a single era. Only the JapaneseCalendar and JapaneseLunisolarCalendar classes support multiple eras.

In the .NET Framework, integers that represent the eras supported by a particular calendar implementation are stored in reverse order in the Calendar.Eras array. The current era is at index zero, and for Calendar classes that support multiple eras, each successive index reflects the previous era. 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. Individual Calendar classes also include static fields that return the value of the current era. They are listed in the following table.

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. The following example calls these methods to retrieve information about era support in the GregorianCalendar class.

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);
      }                        
   }
}
// The example displays the following output: 
//    Date instantiated without an era: 
//    1/1/2 in Japanese Calendar -> 1/1/1990 in Gregorian 
//     
//    Dates instantiated with eras: 
//    1/1/2 era 4 in Japanese Calendar -> 1/1/1990 in Gregorian 
//    1/1/2 era 3 in Japanese Calendar -> 1/1/1927 in Gregorian 
//    1/1/2 era 2 in Japanese Calendar -> 1/1/1913 in Gregorian 
//    1/1/2 era 1 in Japanese Calendar -> 1/1/1869 in Gregorian

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.

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, For example, all four eras of the JapaneseCalendar have years numbered from 1 to 15. Ordinarily, if an era is not specified, both date and time and calendar methods assume that values belong to the current era. To explicitly specify the era when instantiating a date for a Calendar class that supports multiple eras, you can call the Calendar.ToDateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Int32) method. This method enables you to explicitly specify an era along with the calendar's year, month, day, hour, minute, second, and millisecond.

The following example uses the Calendar.ToDateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Int32) method to instantiate the same date, the first month of the first day of the second year, in each era supported by the JapaneseCalendar class. It then displays the date in both the Japanese and Gregorian calendars. It also calls a DateTime constructor to illustrate that methods that create date values without specifying an era create dates in the current 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);
      }                        
   }
}
// The example displays the following output: 
//    Date instantiated without an era: 
//    1/1/2 in Japanese Calendar -> 1/1/1990 in Gregorian 
//     
//    Dates instantiated with eras: 
//    1/1/2 era 4 in Japanese Calendar -> 1/1/1990 in Gregorian 
//    1/1/2 era 3 in Japanese Calendar -> 1/1/1927 in Gregorian 
//    1/1/2 era 2 in Japanese Calendar -> 1/1/1913 in Gregorian 
//    1/1/2 era 1 in Japanese Calendar -> 1/1/1869 in Gregorian

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
Caution note Caution

The JapaneseCalendar class is the only calendar class in the .NET Framework 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.

For all calendars, the "g" custom format specifier includes the era in the result string. 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.      

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. The following example uses the JapaneseLunisolarCalendar class to provide an illustration. 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. (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
Show:
© 2014 Microsoft. All rights reserved.