Export (0) Print
Expand All

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.


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)


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.


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


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 noteImportant

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.


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

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.


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


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

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 noteCaution

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.


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

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.


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


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.

Eras and Era Names

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.


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

Instantiating a Date with an Era

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.


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


Representing Dates in Calendars with Eras

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.


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 


Caution noteCaution

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.


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.      


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


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


Community Additions

ADD
Show:
© 2014 Microsoft