DateTimeFormatInfo 類別

定義

提供關於日期和時間值格式的特定文化特性資訊。Provides culture-specific information about the format of date and time values.

public ref class DateTimeFormatInfo sealed : ICloneable, IFormatProvider
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public sealed class DateTimeFormatInfo : ICloneable, IFormatProvider
type DateTimeFormatInfo = class
    interface ICloneable
    interface IFormatProvider
Public NotInheritable Class DateTimeFormatInfo
Implements ICloneable, IFormatProvider
繼承
DateTimeFormatInfo
屬性
實作

範例

下列範例會使用反映來取得英文(美國) DateTimeFormatInfo文化特性之物件的屬性。The following example uses reflection to get the properties of the DateTimeFormatInfo object for the English (United States) culture. 它會顯示包含自訂格式字串之屬性的值,並使用這些字串來顯示格式化的日期。It displays the value of those properties that contain custom format strings and uses those strings to display formatted dates.

using System;
using System.Globalization;
using System.Reflection;

public class Example
{
   public static void Main()
   {
      // Get the properties of an en-US DateTimeFormatInfo object.
      DateTimeFormatInfo dtfi = CultureInfo.GetCultureInfo("en-US").DateTimeFormat;
      Type typ = dtfi.GetType();
      PropertyInfo[] props = typ.GetProperties();
      DateTime value = new DateTime(2012, 5, 28, 11, 35, 0); 
      
      foreach (var prop in props) {
         // Is this a format pattern-related property?
         if (prop.Name.Contains("Pattern")) {
            string fmt = prop.GetValue(dtfi, null).ToString();
            Console.WriteLine("{0,-33} {1} \n{2,-37}Example: {3}\n", 
                              prop.Name + ":", fmt, "",
                              value.ToString(fmt)); 
         }
      }
   }
}
// The example displays the following output:
//    FullDateTimePattern:              dddd, MMMM dd, yyyy h:mm:ss tt
//                                         Example: Monday, May 28, 2012 11:35:00 AM
//    
//    LongDatePattern:                  dddd, MMMM dd, yyyy
//                                         Example: Monday, May 28, 2012
//    
//    LongTimePattern:                  h:mm:ss tt
//                                         Example: 11:35:00 AM
//    
//    MonthDayPattern:                  MMMM dd
//                                         Example: May 28
//    
//    RFC1123Pattern:                   ddd, dd MMM yyyy HH':'mm':'ss 'GMT'
//                                         Example: Mon, 28 May 2012 11:35:00 GMT
//    
//    ShortDatePattern:                 M/d/yyyy
//                                         Example: 5/28/2012
//    
//    ShortTimePattern:                 h:mm tt
//                                         Example: 11:35 AM
//    
//    SortableDateTimePattern:          yyyy'-'MM'-'dd'T'HH':'mm':'ss
//                                         Example: 2012-05-28T11:35:00
//    
//    UniversalSortableDateTimePattern: yyyy'-'MM'-'dd HH':'mm':'ss'Z'
//                                         Example: 2012-05-28 11:35:00Z
//    
//    YearMonthPattern:                 MMMM, yyyy
//                                         Example: May, 2012
Imports System.Globalization
Imports System.Reflection

Module Example
   Public Sub Main()
      ' Get the properties of an en-US DateTimeFormatInfo object.
      Dim dtfi As DateTimeFormatInfo = CultureInfo.GetCultureInfo("en-US").DateTimeFormat
      Dim typ As Type = dtfi.GetType()
      Dim props() As PropertyInfo = typ.GetProperties()
      Dim value As Date = #05/28/2012 11:35AM# 
      
      For Each prop In props
         ' Is this a format pattern-related property?
         If prop.Name.Contains("Pattern") Then
            Dim fmt As String = CStr(prop.GetValue(dtfi, Nothing))
            Console.WriteLine("{0,-33} {1} {2}{3,-37}Example: {4}", 
                              prop.Name + ":", fmt, vbCrLf, "",
                              value.ToString(fmt)) 
            Console.WriteLine()
         End If
      Next
   End Sub
End Module
' The example displays the following output:
'    FullDateTimePattern:              dddd, MMMM dd, yyyy h:mm:ss tt
'                                         Example: Monday, May 28, 2012 11:35:00 AM
'    
'    LongDatePattern:                  dddd, MMMM dd, yyyy
'                                         Example: Monday, May 28, 2012
'    
'    LongTimePattern:                  h:mm:ss tt
'                                         Example: 11:35:00 AM
'    
'    MonthDayPattern:                  MMMM dd
'                                         Example: May 28
'    
'    RFC1123Pattern:                   ddd, dd MMM yyyy HH':'mm':'ss 'GMT'
'                                         Example: Mon, 28 May 2012 11:35:00 GMT
'    
'    ShortDatePattern:                 M/d/yyyy
'                                         Example: 5/28/2012
'    
'    ShortTimePattern:                 h:mm tt
'                                         Example: 11:35 AM
'    
'    SortableDateTimePattern:          yyyy'-'MM'-'dd'T'HH':'mm':'ss
'                                         Example: 2012-05-28T11:35:00
'    
'    UniversalSortableDateTimePattern: yyyy'-'MM'-'dd HH':'mm':'ss'Z'
'                                         Example: 2012-05-28 11:35:00Z
'    
'    YearMonthPattern:                 MMMM, yyyy
'                                         Example: May, 2012

備註

DateTimeFormatInfo類別的屬性包含用來格式化或剖析日期和時間值的特定文化特性資訊,如下所示:The properties of the DateTimeFormatInfo class contain culture-specific information for formatting or parsing date and time values such as the following:

  • 用來格式化日期值的模式。The patterns used to format date values.

  • 用來格式化時間值的模式。The patterns used to format time values.

  • 一周中的星期幾名稱。The names of the days of the week.

  • 年份的月份名稱。The names of the months of the year.

  • 上午The A.M. 和下午and P.M. 時間值中使用的指示項。designators used in time values.

  • 用來表示日期的行事曆。The calendar in which dates are expressed.

本節內容:In this section:

具現化 DateTimeFormatInfo 物件Instantiating a DateTimeFormatInfo object

DateTimeFormatInfo物件可以表示不因文化特性而異的格式設定慣例、特定文化特性、中性文化特性或目前文化特性。A DateTimeFormatInfo object can represent the formatting conventions of the invariant culture, a specific culture, a neutral culture, or the current culture. 本節討論如何具現化每個DateTimeFormatInfo物件類型。This section discusses how to instantiate each type of DateTimeFormatInfo object.

具現化不因文化特性而異的 DateTimeFormatInfo 物件Instantiating a DateTimeFormatInfo object for the invariant culture

不因文化特性而異,表示不區分文化特性的文化特性。The invariant culture represents a culture that is culture-insensitive. 它是以英文語言為基礎,而不是在任何特定的英文國家/地區。It is based on the English language, but not on any specific English-speaking country/region. 雖然特定文化特性的資料可以是動態的,而且可以變更以反映新的文化慣例或使用者喜好設定,但不變文化特性的資料並不會變更。Although the data of specific cultures can be dynamic and can change to reflect new cultural conventions or user preferences, the data of the invariant culture does not change. 您可以使用下列DateTimeFormatInfo方式,將代表不因文化特性之格式設定慣例的物件具現化:You can instantiate a DateTimeFormatInfo object that represents the formatting conventions of the invariant culture in the following ways:

下列範例會使用這些方法來具現化DateTimeFormatInfo代表不因文化特性而異的物件。The following example uses each of these methods to instantiate a DateTimeFormatInfo object that represents the invariant culture. 然後,它會指出物件是否為唯讀。It then indicates whether the object is read-only.

System.Globalization.DateTimeFormatInfo dtfi; 

dtfi = System.Globalization.DateTimeFormatInfo.InvariantInfo;
Console.WriteLine(dtfi.IsReadOnly);               

dtfi = new System.Globalization.DateTimeFormatInfo();
Console.WriteLine(dtfi.IsReadOnly);               

dtfi = System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat;
Console.WriteLine(dtfi.IsReadOnly);                
// The example displays the following output:
//       True
//       False
//       True      
Dim dtfi As System.Globalization.DateTimeFormatInfo

dtfi = System.Globalization.DateTimeFormatInfo.InvariantInfo
Console.WriteLine(dtfi.IsReadOnly)               

dtfi = New System.Globalization.DateTimeFormatInfo()
Console.WriteLine(dtfi.IsReadOnly)               

dtfi = System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat
Console.WriteLine(dtfi.IsReadOnly) 
' The example displays the following output:
'       True
'       False
'       True      

具現化特定文化特性的 DateTimeFormatInfo 物件Instantiating a DateTimeFormatInfo object for a specific culture

特定的文化特性代表特定國家/地區中所說的語言。A specific culture represents a language that is spoken in a particular country/region. 例如,en-us 是特定文化特性,代表美國所說的英文語言,而 en-us 則是特定文化特性,代表加拿大所說的英文語言。For example, en-US is a specific culture that represents the English language spoken in the United States, and en-CA is a specific culture that represents the English language spoken in Canada. 您可以使用下列DateTimeFormatInfo方式,將代表特定文化特性之格式化慣例的物件具現化:You can instantiate a DateTimeFormatInfo object that represents the formatting conventions of a specific culture in the following ways:

下列範例說明每一種具現化DateTimeFormatInfo物件的方法,並指出產生的物件是否為唯讀。The following example illustrates each of these ways to instantiate a DateTimeFormatInfo object and indicates whether the resulting object is read-only.

System.Globalization.CultureInfo ci = null;
System.Globalization.DateTimeFormatInfo dtfi = null;

// Instantiate a culture using CreateSpecificCulture.
ci = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
dtfi = ci.DateTimeFormat;
Console.WriteLine("{0} from CreateSpecificCulture: {1}", ci.Name, dtfi.IsReadOnly);

// Instantiate a culture using the CultureInfo constructor.
ci = new System.Globalization.CultureInfo("en-CA"); 
dtfi = ci.DateTimeFormat;
Console.WriteLine("{0} from CultureInfo constructor: {1}", ci.Name, dtfi.IsReadOnly);

// Retrieve a culture by calling the GetCultureInfo method.
ci = System.Globalization.CultureInfo.GetCultureInfo("en-AU");
dtfi = ci.DateTimeFormat;
Console.WriteLine("{0} from GetCultureInfo: {1}", ci.Name, dtfi.IsReadOnly);

// Instantiate a DateTimeFormatInfo object by calling DateTimeFormatInfo.GetInstance.  
ci = System.Globalization.CultureInfo.CreateSpecificCulture("en-GB");
dtfi = System.Globalization.DateTimeFormatInfo.GetInstance(ci);
Console.WriteLine("{0} from GetInstance: {1}", ci.Name, dtfi.IsReadOnly);

// The example displays the following output:
//      en-US from CreateSpecificCulture: False
//      en-CA from CultureInfo constructor: False
//      en-AU from GetCultureInfo: True
//      en-GB from GetInstance: False
Dim ci As System.Globalization.CultureInfo = Nothing
Dim dtfi As System.Globalization.DateTimeFormatInfo = Nothing

' Instantiate a culture using CreateSpecificCulture.
ci = System.Globalization.CultureInfo.CreateSpecificCulture("en-US")
dtfi = ci.DateTimeFormat
Console.WriteLine("{0} from CreateSpecificCulture: {1}", ci.Name, dtfi.IsReadOnly)

' Instantiate a culture using the CultureInfo constructor.
ci = new System.Globalization.CultureInfo("en-CA") 
dtfi = ci.DateTimeFormat
Console.WriteLine("{0} from CultureInfo constructor: {1}", ci.Name, dtfi.IsReadOnly)

' Retrieve a culture by calling the GetCultureInfo method.
ci = System.Globalization.CultureInfo.GetCultureInfo("en-AU")
dtfi = ci.DateTimeFormat
Console.WriteLine("{0} from GetCultureInfo: {1}", ci.Name, dtfi.IsReadOnly)


' Instantiate a DateTimeFormatInfo object by calling DateTimeFormatInfo.GetInstance.  
ci = System.Globalization.CultureInfo.CreateSpecificCulture("en-GB")
dtfi = System.Globalization.DateTimeFormatInfo.GetInstance(ci)
Console.WriteLine("{0} from GetInstance: {1}", ci.Name, dtfi.IsReadOnly)

' The example displays the following output:
'      en-US from CreateSpecificCulture: False
'      en-CA from CultureInfo constructor: False
'      en-AU from GetCultureInfo: True
'      en-GB from GetInstance: False

為中性文化特性具現化 DateTimeFormatInfo 物件Instantiating a DateTimeFormatInfo object for a neutral culture

中性文化特性代表與國家/地區無關的文化特性或語言;它通常是一或多個特定文化特性的父系。A neutral culture represents a culture or language that is independent of a country/region; it is typically the parent of one or more specific cultures. 例如,Fr 是法文語言的中性文化特性,以及 fr-fr 文化特性的父系。For example, Fr is a neutral culture for the French language and the parent of the fr-FR culture. 您可以使用您DateTimeFormatInfo DateTimeFormatInfo建立物件的相同方式,將表示中性文化特性之格式設定慣例的物件具現化,以表示特定文化特性的格式設定慣例。You can instantiate a DateTimeFormatInfo object that represents the formatting conventions of a neutral culture in the same ways that you create a DateTimeFormatInfo object that represents the formatting conventions of a specific culture. 此外,您可以從DateTimeFormatInfo特定文化特性的CultureInfo.Parent屬性抓取中性文化特性,並抓取其CultureInfo.DateTimeFormat屬性所傳回的DateTimeFormatInfo物件,藉此抓取中性文化特性的物件。In addition, you can retrieve a neutral culture's DateTimeFormatInfo object by retrieving a neutral culture from a specific culture's CultureInfo.Parent property and retrieving the DateTimeFormatInfo object returned by its CultureInfo.DateTimeFormat property. 除非父系文化特性表示不因文化特性而異DateTimeFormatInfo ,否則傳回的物件為讀取/寫入。Unless the parent culture represents the invariant culture, the returned DateTimeFormatInfo object is read/write. 下列範例說明如何將表示中性文化特性DateTimeFormatInfo的物件具現化。The following example illustrates these ways of instantiating a DateTimeFormatInfo object that represents a neutral culture.

 System.Globalization.CultureInfo specific, neutral;
 System.Globalization.DateTimeFormatInfo dtfi;

 // Instantiate a culture by creating a specific culture and using its Parent property.
 specific = System.Globalization.CultureInfo.GetCultureInfo("fr-FR");
 neutral = specific.Parent;
 dtfi = neutral.DateTimeFormat;
 Console.WriteLine("{0} from Parent property: {1}", neutral.Name, dtfi.IsReadOnly);
 
 dtfi = System.Globalization.CultureInfo.GetCultureInfo("fr-FR").Parent.DateTimeFormat;
 Console.WriteLine("{0} from Parent property: {1}", neutral.Name, dtfi.IsReadOnly);

 // Instantiate a neutral culture using the CultureInfo constructor.
 neutral = new System.Globalization.CultureInfo("fr");
 dtfi = neutral.DateTimeFormat;
 Console.WriteLine("{0} from CultureInfo constructor: {1}", neutral.Name, dtfi.IsReadOnly);
 
 // Instantiate a culture using CreateSpecificCulture. 
 neutral = System.Globalization.CultureInfo.CreateSpecificCulture("fr");
 dtfi = neutral.DateTimeFormat;
 Console.WriteLine("{0} from CreateSpecificCulture: {1}", neutral.Name, dtfi.IsReadOnly);
 
 // Retrieve a culture by calling the GetCultureInfo method.
 neutral = System.Globalization.CultureInfo.GetCultureInfo("fr");
 dtfi = neutral.DateTimeFormat;
 Console.WriteLine("{0} from GetCultureInfo: {1}", neutral.Name, dtfi.IsReadOnly);

 // Instantiate a DateTimeFormatInfo object by calling GetInstance.  
 neutral = System.Globalization.CultureInfo.CreateSpecificCulture("fr");
 dtfi = System.Globalization.DateTimeFormatInfo.GetInstance(neutral);
 Console.WriteLine("{0} from GetInstance: {1}", neutral.Name, dtfi.IsReadOnly);

 // The example displays the following output:
 //       fr from Parent property: False
 //       fr from Parent property: False
 //       fr from CultureInfo constructor: False
 //       fr-FR from CreateSpecificCulture: False
 //       fr from GetCultureInfo: True
 //       fr-FR from GetInstance: False      
 Dim specific, neutral As System.Globalization.CultureInfo
 Dim dtfi As System.Globalization.DateTimeFormatInfo

 ' Instantiate a culture by creating a specific culture and using its Parent property.
 specific = System.Globalization.CultureInfo.GetCultureInfo("fr-FR")
 neutral = specific.Parent
 dtfi = neutral.DateTimeFormat
 Console.WriteLine("{0} from Parent property: {1}", neutral.Name, dtfi.IsReadOnly)
 
 dtfi = System.Globalization.CultureInfo.GetCultureInfo("fr-FR").Parent.DateTimeFormat
 Console.WriteLine("{0} from Parent property: {1}", neutral.Name, dtfi.IsReadOnly)

 ' Instantiate a neutral culture using the CultureInfo constructor.
 neutral = New System.Globalization.CultureInfo("fr")
 dtfi = neutral.DateTimeFormat
 Console.WriteLine("{0} from CultureInfo constructor: {1}", neutral.Name, dtfi.IsReadOnly)

 ' Instantiate a culture using CreateSpecificCulture. 
 neutral = System.Globalization.CultureInfo.CreateSpecificCulture("fr")
 dtfi = neutral.DateTimeFormat
 Console.WriteLine("{0} from CreateSpecificCulture: {1}", neutral.Name, dtfi.IsReadOnly)
 
 ' Retrieve a culture by calling the GetCultureInfo method.
 neutral = System.Globalization.CultureInfo.GetCultureInfo("fr")
 dtfi = neutral.DateTimeFormat
 Console.WriteLine("{0} from GetCultureInfo: {1}", neutral.Name, dtfi.IsReadOnly)
 
 ' Instantiate a DateTimeFormatInfo object by calling GetInstance.  
 neutral = System.Globalization.CultureInfo.CreateSpecificCulture("fr")
 dtfi = System.Globalization.DateTimeFormatInfo.GetInstance(neutral)
 Console.WriteLine("{0} from GetInstance: {1}", neutral.Name, dtfi.IsReadOnly)

 ' The example displays the following output:
 '       fr from Parent property: False
 '       fr from Parent property: False
 '       fr from CultureInfo constructor: False
 '       fr-FR from CreateSpecificCulture: False
 '       fr from GetCultureInfo: True
 '       fr-FR from GetInstance: False       

注意

在 .NET Framework 版本1.0 至.NET Framework 3.5.NET Framework 3.5中,嘗試DateTimeFormatInfo取出反映中性文化NotSupportedException特性之格式化慣例的物件會擲回例外狀況。In the .NET Framework versions 1.0 through .NET Framework 3.5.NET Framework 3.5, trying to retrieve a DateTimeFormatInfo object that reflects the formatting conventions of a neutral culture throws a NotSupportedException exception.

不過,中性文化特性缺少特定文化特性格式資訊,因為它與特定國家/地區無關。However, a neutral culture lacks culture-specific formatting information, because it is independent of a specific country/region. .NET Framework 會傳回一個DateTimeFormatInfo物件,它會反映特定文化特性的格式設定慣例,這是中性文化特性的子系,而不是以泛型值填入物件。DateTimeFormatInfoInstead of populating the DateTimeFormatInfo object with generic values, the .NET Framework returns a DateTimeFormatInfo object that reflects the formatting conventions of a specific culture that is a child of the neutral culture. 例如, DateTimeFormatInfo中性 en 文化特性的物件會反映 en-us 文化特性的格式設定慣例, DateTimeFormatInfo而 fr 文化特性的物件會反映 fr-fr 文化特性的格式設定慣例。For example, the DateTimeFormatInfo object for the neutral en culture reflects the formatting conventions of the en-US culture, and the DateTimeFormatInfo object for the fr culture reflects the formatting conventions of the fr-FR culture.

您可以使用類似下列的程式碼,來判斷中性文化特性所代表的特定文化特性格式慣例。You can use code like the following to determine which specific culture's formatting conventions a neutral culture represents. 此範例會使用反映,將DateTimeFormatInfo中性文化特性的屬性與特定子文化特性的屬性進行比較。The example uses reflection to compare the DateTimeFormatInfo properties of a neutral culture with the properties of a specific child culture. 如果兩個行事曆的日曆類型相同,則會將其視為相等,如果是西曆,則GregorianCalendar.CalendarType會將其屬性的值相同。It considers two calendars to be equivalent if they are the same calendar type and, for Gregorian calendars, if their GregorianCalendar.CalendarType properties have identical values.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;

public class Example
{
   public static void Main()
   {
      // Get all the neutral cultures
      List<String> names = new List<String>();
      Array.ForEach(CultureInfo.GetCultures(CultureTypes.NeutralCultures),
                    culture => names.Add(culture.Name));
      names.Sort();
      foreach (var name in names) {
         // Ignore the invariant culture.
         if (name == "") continue;
         
         ListSimilarChildCultures(name);        
      }
   }

   private static void ListSimilarChildCultures(String name)
   {
      // Create the neutral DateTimeFormatInfo object.
      DateTimeFormatInfo dtfi = CultureInfo.GetCultureInfo(name).DateTimeFormat;
      // Retrieve all specific cultures of the neutral culture.
      CultureInfo[] cultures = Array.FindAll(CultureInfo.GetCultures(CultureTypes.SpecificCultures), 
                               culture => culture.Name.StartsWith(name + "-", StringComparison.OrdinalIgnoreCase));
      // Create an array of DateTimeFormatInfo properties
      PropertyInfo[] properties = typeof(DateTimeFormatInfo).GetProperties(BindingFlags.Instance | BindingFlags.Public);
      bool hasOneMatch = false;

      foreach (var ci in cultures) {
         bool match = true;     
         // Get the DateTimeFormatInfo for a specific culture.
         DateTimeFormatInfo specificDtfi = ci.DateTimeFormat;
         // Compare the property values of the two.
         foreach (var prop in properties) {
            // We're not interested in the value of IsReadOnly.     
            if (prop.Name == "IsReadOnly") continue;
            
            // For arrays, iterate the individual elements to see if they are the same.
            if (prop.PropertyType.IsArray) { 
               IList nList = (IList) prop.GetValue(dtfi, null);
               IList sList = (IList) prop.GetValue(specificDtfi, null);
               if (nList.Count != sList.Count) {
                  match = false;
Console.WriteLine("   Different n in {2} array for {0} and {1}", name, ci.Name, prop.Name);
                  break;
               } 

               for (int ctr = 0; ctr < nList.Count; ctr++) {
                  if (! nList[ctr].Equals(sList[ctr])) { 
                     match = false;
Console.WriteLine("   {0} value different for {1} and {2}", prop.Name, name, ci.Name);                     
                     break;
                  }     
               }
               
               if (! match) break;
            }
            // Get non-array values.
            else {
               Object specificValue = prop.GetValue(specificDtfi);
               Object neutralValue = prop.GetValue(dtfi);
                               
               // Handle comparison of Calendar objects.
               if (prop.Name == "Calendar") { 
                  // The cultures have a different calendar type.
                  if (specificValue.ToString() != neutralValue.ToString()) {
Console.WriteLine("   Different calendar types for {0} and {1}", name, ci.Name);
                     match = false;
                     break;
                  }
                   
                  if (specificValue is GregorianCalendar) {
                     if (((GregorianCalendar) specificValue).CalendarType != ((GregorianCalendar) neutralValue).CalendarType) {
Console.WriteLine("   Different Gregorian calendar types for {0} and {1}", name, ci.Name);
                        match = false;
                        break;
                     }
                  }
               }
               else if (! specificValue.Equals(neutralValue)) {
                  match = false;
Console.WriteLine("   Different {0} values for {1} and {2}", prop.Name, name, ci.Name);                  
                  break;   
               }
            }        
         }
         if (match) {
            Console.WriteLine("DateTimeFormatInfo object for '{0}' matches '{1}'", 
                              name, ci.Name);
            hasOneMatch = true;
         }                                       
      }
      if (! hasOneMatch)
         Console.WriteLine("DateTimeFormatInfo object for '{0}' --> No Match", name);            

      Console.WriteLine();
   }
}
Imports System.Collections
Imports System.Collections.Generic
Imports System.Globalization
Imports System.Reflection

Module Example
   Public Sub Main()
      ' Get all the neutral cultures
      Dim names As New List(Of String)
      Array.ForEach(CultureInfo.GetCultures(CultureTypes.NeutralCultures),
                    Sub(culture) names.Add(culture.Name))
      names.Sort()
      For Each name In names
         ' Ignore the invariant culture.
         If name = "" Then Continue For
         
         ListSimilarChildCultures(name)        
      Next
   End Sub

   Private Sub ListSimilarChildCultures(name As String)
      ' Create the neutral DateTimeFormatInfo object.
      Dim dtfi As DateTimeFormatInfo = CultureInfo.GetCultureInfo(name).DateTimeFormat
      ' Retrieve all specific cultures of the neutral culture.
      Dim cultures() As CultureInfo = Array.FindAll(CultureInfo.GetCultures(CultureTypes.SpecificCultures), 
                               Function(culture) culture.Name.StartsWith(name + "-", StringComparison.OrdinalIgnoreCase))
      ' Create an array of DateTimeFormatInfo properties
      Dim properties() As PropertyInfo = GetType(DateTimeFormatInfo).GetProperties(BindingFlags.Instance Or BindingFlags.Public)
      Dim hasOneMatch As Boolean = False

      For Each ci In cultures
         Dim match As Boolean = True     
         ' Get the DateTimeFormatInfo for a specific culture.
         Dim specificDtfi As DateTimeFormatInfo = ci.DateTimeFormat
         ' Compare the property values of the two.
         For Each prop In properties
            ' We're not interested in the value of IsReadOnly.     
            If prop.Name = "IsReadOnly" Then Continue For
            
            ' For arrays, iterate the individual elements to see if they are the same.
            If prop.PropertyType.IsArray Then 
               Dim nList As IList = CType(prop.GetValue(dtfi, Nothing), IList)
               Dim sList As IList = CType(prop.GetValue(specificDtfi, Nothing), IList)
               If nList.Count <> sList.Count Then
                  match = false
Console.WriteLine("   Different n in {2} array for {0} and {1}", name, ci.Name, prop.Name)
                  Exit For
               End If 

               For ctr As Integer = 0 To nList.Count - 1
                  If Not nList(ctr).Equals(sList(ctr)) 
                     match = false
Console.WriteLine("   {0} value different for {1} and {2}", prop.Name, name, ci.Name)                     
                     Exit For
                  End If     
               Next
               
               If Not match Then Exit For
            ' Get non-array values.
            Else
               Dim specificValue As Object = prop.GetValue(specificDtfi)
               Dim neutralValue As Object = prop.GetValue(dtfi)
                               
               ' Handle comparison of Calendar objects.
               If prop.Name = "Calendar" Then 
                  ' The cultures have a different calendar type.
                  If specificValue.ToString() <> neutralValue.ToString() Then
Console.WriteLine("   Different calendar types for {0} and {1}", name, ci.Name)
                     match = False
                     Exit For
                  End If
                   
                  If TypeOf specificValue Is GregorianCalendar Then
                     If CType(specificValue, GregorianCalendar).CalendarType <> CType(neutralValue, GregorianCalendar).CalendarType Then
Console.WriteLine("   Different Gregorian calendar types for {0} and {1}", name, ci.Name)
                        match = False
                        Exit For
                     End If
                  End If
               Else If Not specificValue.Equals(neutralValue) Then
                  match = false
Console.WriteLine("   Different {0} values for {1} and {2}", prop.Name, name, ci.Name)                  
                  Exit For   
               End If
            End If        
         Next
         If match Then
            Console.WriteLine("DateTimeFormatInfo object for '{0}' matches '{1}'", 
                                      name, ci.Name)
            hasOneMatch = True
         End If                                       
      Next
      If Not hasOneMatch Then
         Console.WriteLine("DateTimeFormatInfo object for '{0}' --> No Match", name)            
      End If
      
      Console.WriteLine()
   End Sub
End Module

將目前文化特性的 DateTimeFormatInfo 物件具現化Instantiating a DateTimeFormatInfo object for the current culture

您可以使用下列DateTimeFormatInfo方式,將代表目前文化特性之格式化慣例的物件具現化:You can instantiate a DateTimeFormatInfo object that represents the formatting conventions of the current culture in the following ways:

下列範例會使用上述每個方法來具現DateTimeFormatInfo化物件,該物件代表目前文化特性的格式化慣例。The following example uses each of these methods to instantiate a DateTimeFormatInfo object that represents the formatting conventions of the current culture. 然後,它會指出物件是否為唯讀。It then indicates whether the object is read-only.

DateTimeFormatInfo dtfi;

dtfi = DateTimeFormatInfo.CurrentInfo;
Console.WriteLine(dtfi.IsReadOnly);

dtfi = CultureInfo.CurrentCulture.DateTimeFormat;
Console.WriteLine(dtfi.IsReadOnly);

dtfi = DateTimeFormatInfo.GetInstance(CultureInfo.CurrentCulture);
Console.WriteLine(dtfi.IsReadOnly);
// The example displays the following output:
//     True
//     True
//     True
Dim dtfi As DateTimeFormatInfo

dtfi = DateTimeFormatInfo.CurrentInfo
Console.WriteLine(dtfi.IsReadOnly)

dtfi = CultureInfo.CurrentCulture.DateTimeFormat
Console.WriteLine(dtfi.IsReadOnly)

dtfi = DateTimeFormatInfo.GetInstance(CultureInfo.CurrentCulture)
Console.WriteLine(dtfi.IsReadOnly)
' The example displays the following output:
'     True
'     True
'     True

您可以使用下列其中DateTimeFormatInfo一種方式來建立可寫入的物件,以代表目前線程文化特性的慣例:You can create a writable DateTimeFormatInfo object that represents the conventions of the current thread culture in one of these ways:

下列範例說明每個具現化讀取/寫入DateTimeFormatInfo物件,並顯示其IsReadOnly屬性值的方式。The following example illustrates each way of instantiating a read/write DateTimeFormatInfo object and displays the value of its IsReadOnly property.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      DateTimeFormatInfo current1 = DateTimeFormatInfo.CurrentInfo;
      current1 = (DateTimeFormatInfo) current1.Clone();
      Console.WriteLine(current1.IsReadOnly);

      CultureInfo culture2 = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name);
      DateTimeFormatInfo current2 = culture2.DateTimeFormat;
      Console.WriteLine(current2.IsReadOnly);
   }
}
// The example displays the following output:
//       False
//       False
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim current1 As DateTimeFormatInfo = DateTimeFormatInfo.CurrentInfo
      current1 = CType(current1.Clone(), DateTimeFormatInfo)
      Console.WriteLine(current1.IsReadOnly)

      Dim culture2 As CultureInfo = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name)
      Dim current2 As DateTimeFormatInfo = culture2.DateTimeFormat
      Console.WriteLine(current2.IsReadOnly)
   End Sub
End Module
' The example displays the following output:
'       False
'       False

在 Windows 中,使用者可以透過 [控制台] DateTimeFormatInfo中的 [地區和語言] 應用程式,覆寫一些用於格式化和剖析作業的屬性值。In Windows, the user can override some of the DateTimeFormatInfo property values used in formatting and parsing operations through the Region and Language application in Control Panel. 例如,其文化特性為英文(美國)的使用者可能會選擇使用24小時制(格式為 HH: mm: ss)來顯示長時間值,而不是預設的12小時制(格式為 h:mm: ss tt)。For example, a user whose culture is English (United States) might choose to display long time values using a 24-hour clock (in the format HH:mm:ss) instead of the default 12-hour clock (in the format h:mm:ss tt). DateTimeFormatInfo先前討論的方式取得的物件會反映這些使用者覆寫。The DateTimeFormatInfo objects retrieved in the ways discussed previously all reflect these user overrides. 如果不想要這樣做,您可以NumberFormatInfo藉由CultureInfo.CultureInfo(String, Boolean)呼叫函式false並為useUserOverride引數提供的值,來建立不會反映使用者覆寫的物件(而且也是讀取/寫入,而不是唯讀)。If this is undesirable, you can create a NumberFormatInfo object that does not reflect user overrides (and is also read/write instead of read-only) by calling the CultureInfo.CultureInfo(String, Boolean) constructor and supplying a value of false for the useUserOverride argument. 下列範例會針對目前文化特性是英文(美國)且其完整時間模式已從預設值 h:mm: ss tt 變更為 HH: mm: ss 的系統說明這種情況。The following example illustrates this for a system whose current culture is English (United States) and whose long time pattern has been changed from the default of h:mm:ss tt to HH:mm:ss.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      CultureInfo culture;
      DateTimeFormatInfo dtfi;
      
      culture = CultureInfo.CurrentCulture;
      dtfi = culture.DateTimeFormat;
      Console.WriteLine("Culture Name:      {0}", culture.Name);
      Console.WriteLine("User Overrides:    {0}", culture.UseUserOverride);
      Console.WriteLine("Long Time Pattern: {0}\n", culture.DateTimeFormat.LongTimePattern);
            
      culture = new CultureInfo(CultureInfo.CurrentCulture.Name, false);
      Console.WriteLine("Culture Name:      {0}",   culture.Name);
      Console.WriteLine("User Overrides:    {0}",   culture.UseUserOverride);
      Console.WriteLine("Long Time Pattern: {0}\n", culture.DateTimeFormat.LongTimePattern);
   }
}
// The example displays the following output:
//       Culture Name:      en-US
//       User Overrides:    True
//       Long Time Pattern: HH:mm:ss
//       
//       Culture Name:      en-US
//       User Overrides:    False
//       Long Time Pattern: h:mm:ss tt
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim culture As CultureInfo
      Dim dtfi As DateTimeFormatInfo
      
      culture = CultureInfo.CurrentCulture
      dtfi = culture.DateTimeFormat
      Console.WriteLine("Culture Name:      {0}", culture.Name)
      Console.WriteLine("User Overrides:    {0}", culture.UseUserOverride)
      Console.WriteLine("Long Time Pattern: {0}", culture.DateTimeFormat.LongTimePattern)
      Console.WriteLine()
            
      culture = New CultureInfo(CultureInfo.CurrentCulture.Name, False)
      Console.WriteLine("Culture Name:      {0}", culture.Name)
      Console.WriteLine("User Overrides:    {0}", culture.UseUserOverride)
      Console.WriteLine("Long Time Pattern: {0}", culture.DateTimeFormat.LongTimePattern)
   End Sub
End Module
' The example displays the following output:
'       Culture Name:      en-US
'       User Overrides:    True
'       Long Time Pattern: HH:mm:ss
'       
'       Culture Name:      en-US
'       User Overrides:    False
'       Long Time Pattern: h:mm:ss tt

DateTimeFormatInfo 和動態資料DateTimeFormatInfo and dynamic data

DateTimeFormatInfo類別提供的日期和時間值格式的特定文化特性資料是動態的,就像類別所CultureInfo提供的文化特性資料一樣。The culture-specific data for formatting date and time values provided by the DateTimeFormatInfo class is dynamic, just like cultural data provided by the CultureInfo class. 對於DateTimeFormatInfo與特定CultureInfo物件相關聯之物件的值,您不應該進行任何的假設。You should not make any assumptions about the stability of values for DateTimeFormatInfo objects that are associated with particular CultureInfo objects. 只有不因文化特性而異的資料與其相關DateTimeFormatInfo聯的物件,才是穩定的。Only the data provided by the invariant culture and its associated DateTimeFormatInfo object is stable. 其他資料可能會在應用程式會話之間變更,甚至是在您的應用程式執行時也一樣。Other data can change between application sessions or even while your application is running. 有四個主要的變更來源:There are four major sources of change:

  • 系統更新。System updates. 如慣用行事曆或慣用日期和時間格式等文化喜好設定會隨著時間變更。Cultural preferences such as the preferred calendar or customary date and time formats change over time. 發生這種情況時,Windows Update 包含特定DateTimeFormatInfo文化特性之屬性值的變更。When this happens, Windows Update includes changes to the DateTimeFormatInfo property value for a particular culture.

  • 取代文化特性。Replacement cultures. CultureAndRegionInfoBuilder類別可以用來取代現有文化特性的資料。The CultureAndRegionInfoBuilder class can be used to replace the data of an existing culture.

  • 屬性值的串聯變更。Cascading changes to property values. 許多與文化特性相關的屬性可能會在執行時間變更,而這會導致DateTimeFormatInfo資料變更。A number of culture-related properties can change at run time, which, in turn, causes DateTimeFormatInfo data to change. 例如,您可以用程式設計方式或透過使用者動作來變更目前的文化特性。For example, the current culture can be changed either programmatically or through user action. 發生這種情況時DateTimeFormatInfoCurrentInfo屬性傳回的物件會變更為與目前文化特性相關聯的物件。When this happens, the DateTimeFormatInfo object returned by the CurrentInfo property changes to an object associated with the current culture. 同樣地,文化特性的行事曆也可以變更,這可能會造成DateTimeFormatInfo許多屬性值的變更。Similarly, a culture's calendar can change, which can result in changes to numerous DateTimeFormatInfo property values.

  • 使用者喜好設定。User preferences. 您的應用程式使用者可能會選擇透過 [控制台] 中的 [地區及語言選項],覆寫與目前系統文化特性相關聯的一些值。Users of your application might choose to override some of the values associated with the current system culture through the regional and language options in Control Panel. 例如,使用者可能會選擇以不同的格式來顯示日期。For example, users might choose to display the date in a different format. 如果屬性設定trueDateTimeFormatInfo ,則也會從使用者設定中抓取物件的屬性。 CultureInfo.UseUserOverrideIf the CultureInfo.UseUserOverride property is set to true, the properties of the DateTimeFormatInfo object is also retrieved from the user settings. 如果使用者設定與CultureInfo物件相關聯的文化OptionalCalendars特性不相容(例如,如果選取的行事曆不是屬性所指示的其中一個行事曆),則方法的結果和屬性的值未定義。If the user settings are incompatible with the culture associated with the CultureInfo object (for example, if the selected calendar is not one of the calendars indicated by the OptionalCalendars property), the results of the methods and the values of the properties are undefined.

若要將不一致資料的可能性降到最低, DateTimeFormatInfo物件的所有使用者可覆寫屬性都會在建立物件時初始化。To minimize the possibility of inconsistent data, all user-overridable properties of a DateTimeFormatInfo object are initialized when the object is created. 仍然有可能會造成不一致的情況,因為物件建立或使用者覆寫程式都不是不可部分完成的,而且相關的值可能會在物件建立期間變更。There is still a possibility of inconsistency, because neither object creation nor the user override process is atomic and the relevant values can change during object creation. 不過,這種情況應該非常罕見。However, this situation should be extremely rare.

您可以控制是否要在代表與系統DateTimeFormatInfo文化特性相同文化特性的物件中反映使用者覆寫。You can control whether user overrides are reflected in DateTimeFormatInfo objects that represent the same culture as the system culture. 下表列出DateTimeFormatInfo物件的抓取方式,並指出產生的物件是否會反映使用者覆寫。The following table lists the ways in which a DateTimeFormatInfo object can be retrieved and indicates whether the resulting object reflects user overrides.

CultureInfo 和 DateTimeFormatInfo 物件的來源Source of CultureInfo and DateTimeFormatInfo object 反映使用者覆寫Reflects user overrides
CultureInfo.CurrentCulture.DateTimeFormat 屬性CultureInfo.CurrentCulture.DateTimeFormat property Yes
DateTimeFormatInfo.CurrentInfo 屬性DateTimeFormatInfo.CurrentInfo property [是]Yes
CultureInfo.CreateSpecificCulture 方法CultureInfo.CreateSpecificCulture method Yes
CultureInfo.GetCultureInfo 方法CultureInfo.GetCultureInfo method No
CultureInfo.CultureInfo(String) 建構函式CultureInfo.CultureInfo(String) constructor Yes
CultureInfo.CultureInfo(String, Boolean) 建構函式CultureInfo.CultureInfo(String, Boolean) constructor 取決於參數的useUserOverrideDepends on value of useUserOverride parameter

除非有合理的理由要這麼做,否則當您在用戶端應用程式中使用DateTimeFormatInfo物件來格式化和剖析使用者輸入或顯示資料時,您應該尊重使用者覆寫。Unless there is a compelling reason to do otherwise, you should respect user overrides when you use the DateTimeFormatInfo object in client applications to format and parse user input or to display data. 若為伺服器應用程式或自動應用程式,您就不應該這樣做。For server applications or unattended applications, you should not. 不過,如果您以明確或DateTimeFormatInfo隱含方式使用物件,以字串形式保存日期和時間資料,您應該DateTimeFormatInfo使用反映不因文化特性而異的格式設定慣例的物件,或者您應該指定您使用的自訂日期和時間格式字串,無論文化特性為何。However, if you are using the DateTimeFormatInfo object either explicitly or implicitly to persist date and time data in string form, you should either use a DateTimeFormatInfo object that reflects the formatting conventions of the invariant culture, or you should specify a custom date and time format string that you use regardless of culture.

格式化日期和時間Formatting dates and times

在所有日期和時間格式化作業中,會隱含或明確使用物件。DateTimeFormatInfoA DateTimeFormatInfo object is used implicitly or explicitly in all date and time formatting operations. 這些包括呼叫下列方法:These include calls to the following methods:

所有日期和時間格式作業都會使用實作為IFormatProviderAll date and time formatting operations make use of an IFormatProvider implementation. 介面包含單一IFormatProvider.GetFormat(Type)方法。 IFormatProviderThe IFormatProvider interface includes a single method, IFormatProvider.GetFormat(Type). 這個回呼方法會傳遞Type物件,代表提供格式設定資訊所需的類型。This callback method is passed a Type object that represents the type needed to provide formatting information. 方法會傳回該類型null的實例,如果無法提供類型的實例,則傳回。The method returns either an instance of that type or null if it cannot provide an instance of the type. .NET Framework 包括格式化日期IFormatProvider和時間的兩個設定:The .NET Framework includes two IFormatProvider implementations for formatting dates and times:

如果未IFormatProvider將實作為明確提供給格式化方法CultureInfo ,則會使用代表目前線程CultureInfo.CurrentCulture文化特性之屬性所傳回的物件。If an IFormatProvider implementation is not provided to a formatting method explicitly, the CultureInfo object returned by the CultureInfo.CurrentCulture property that represents the current thread culture is used.

下列範例說明格式化作業中IFormatProvider介面DateTimeFormatInfo和類別之間的關聯性。The following example illustrates the relationship between the IFormatProvider interface and the DateTimeFormatInfo class in formatting operations. 它會定義自IFormatProvider定義的GetFormat執行,其方法會顯示格式化作業所要求的物件類型。It defines a custom IFormatProvider implementation whose GetFormat method displays the type of the object requested by the formatting operation. 如果要求DateTimeFormatInfo物件,方法會DateTimeFormatInfo提供目前線程文化特性的物件。If it is requesting a DateTimeFormatInfo object, the method provides the DateTimeFormatInfo object for the current thread culture. 如範例的Decimal.ToString(IFormatProvider)輸出所示,方法會DateTimeFormatInfo要求物件提供String.Format(IFormatProvider, String, Object[])格式資訊NumberFormatInfo ,而ICustomFormatter方法會要求和DateTimeFormatInfo物件以及實作.As the output from the example shows, the Decimal.ToString(IFormatProvider) method requests a DateTimeFormatInfo object to provide formatting information, whereas the String.Format(IFormatProvider, String, Object[]) method requests NumberFormatInfo and DateTimeFormatInfo objects as well as an ICustomFormatter implementation.

using System;
using System.Globalization;

public class CurrentCultureFormatProvider : IFormatProvider
{
   public Object GetFormat(Type formatType) 
   {
      Console.WriteLine("Requesting an object of type {0}", 
                        formatType.Name);
      if (formatType == typeof(NumberFormatInfo))
         return NumberFormatInfo.CurrentInfo;
      else if (formatType == typeof(DateTimeFormatInfo))
         return DateTimeFormatInfo.CurrentInfo;
      else
         return null;
   }
}

public class Example
{
   public static void Main()
   {
      DateTime dateValue = new DateTime(2013, 5, 28, 12, 30, 0);
      string value = dateValue.ToString("F", new CurrentCultureFormatProvider());
      Console.WriteLine(value);
      Console.WriteLine();
      string composite = String.Format(new CurrentCultureFormatProvider(), 
                                       "Date: {0:d}   Amount: {1:C}   Description: {2}",
                                       dateValue, 1264.03m, "Service Charge");
      Console.WriteLine(composite);
      Console.WriteLine();
   }
}
// The example displays output like the following:
//       Requesting an object of type DateTimeFormatInfo
//       Tuesday, May 28, 2013 1:30:00 PM
//       
//       Requesting an object of type ICustomFormatter
//       Requesting an object of type DateTimeFormatInfo
//       Requesting an object of type NumberFormatInfo
//       Date: 5/28/2013   Amount: $1,264.03   Description: Service Charge
Imports System.Globalization

Public Class CurrentCultureFormatProvider : Implements IFormatProvider
   Public Function GetFormat(formatType As Type) As Object _
                   Implements IFormatProvider.GetFormat
      Console.WriteLine("Requesting an object of type {0}", 
                        formatType.Name)
      If formatType Is GetType(NumberFormatInfo) Then
         Return NumberFormatInfo.CurrentInfo
      Else If formatType Is GetType(DateTimeFormatInfo) Then
         Return DateTimeFormatInfo.CurrentInfo
      Else
         Return Nothing
      End If
   End Function
End Class

Module Example
   Public Sub Main()
      Dim dateValue As New Date(2013, 05, 28, 13, 30, 0)
      Dim value As String = dateValue.ToString("F", New CurrentCultureFormatProvider())
      Console.WriteLine(value)
      Console.WriteLine()
      Dim composite As String = String.Format(New CurrentCultureFormatProvider, 
                                              "Date: {0:d}   Amount: {1:C}   Description: {2}",
                                              dateValue, 1264.03d, "Service Charge")
      Console.WriteLine(composite)
      Console.WriteLine()
   End Sub
End Module
' The example displays output like the following:
'       Requesting an object of type DateTimeFormatInfo
'       Tuesday, May 28, 2013 1:30:00 PM
'       
'       Requesting an object of type ICustomFormatter
'       Requesting an object of type DateTimeFormatInfo
'       Requesting an object of type NumberFormatInfo
'       Date: 5/28/2013   Amount: $1,264.03   Description: Service Charge

格式字串和 DateTimeFormatInfo 屬性Format strings and DateTimeFormatInfo properties

DateTimeFormatInfo物件包含三種屬性,用於以日期和時間值格式化作業:The DateTimeFormatInfo object includes three kinds of properties that are used in formatting operations with date and time values:

標準日期和時間格式字串(例如 "d"、"d"、"f" 和 "f")是對應至特定DateTimeFormatInfo格式模式屬性的別名。The standard date and time format strings, such as "d", "D", "f", and "F", are aliases that correspond to particular DateTimeFormatInfo format pattern properties. 大部分的自訂日期和時間格式字串都與格式化作業插入結果資料流程的字串或子字串相關。Most of the custom date and time format strings are related to strings or substrings that a formatting operation inserts into the result stream. 下表列出標準和自訂日期和時間格式規範,以及其相關DateTimeFormatInfo聯的屬性。The following table lists the standard and custom date and time format specifiers and their associated DateTimeFormatInfo properties. 如需如何使用這些格式規範的詳細資訊,請參閱標準日期和時間格式字串自訂日期和時間格式字串For details about how to use these format specifiers, see Standard Date and Time Format Strings and Custom Date and Time Format Strings. 請注意,每個標準格式字串都會DateTimeFormatInfo對應至屬性,其值為自訂日期和時間格式字串。Note that each standard format string corresponds to a DateTimeFormatInfo property whose value is a custom date and time format string. 這個自訂格式字串中的個別規範又會對應到DateTimeFormatInfo其他屬性。The individual specifiers in this custom format string in turn correspond to other DateTimeFormatInfo properties. 資料表只DateTimeFormatInfo會列出標準格式字串為別名的屬性,而且不會列出指派給那些別名屬性的自訂格式字串所能存取的屬性。The table lists only the DateTimeFormatInfo properties for which the standard format strings are aliases, and does not list properties that may be accessed by custom format strings assigned to those aliased properties. 此外,資料表只會列出對應至DateTimeFormatInfo屬性的自訂格式規範。In addition, the table lists only custom format specifiers that correspond to DateTimeFormatInfo properties.

格式規範Format specifier 相關聯的屬性Associated properties
"d" (簡短日期; 標準格式字串)"d" (short date; standard format string) ShortDatePattern,用來定義結果字串的整體格式。ShortDatePattern, to define the overall format of the result string.
"D" (完整日期; 標準格式字串)"D" (long date; standard format string) LongDatePattern,用來定義結果字串的整體格式。LongDatePattern, to define the overall format of the result string.
"f" (完整日期/短時間; 標準格式字串)"f" (full date / short time; standard format string) LongDatePattern,用來定義結果字串的日期元件格式。LongDatePattern, to define the format of the date component of the result string.

ShortTimePattern,用來定義結果字串的時間元件格式。ShortTimePattern, to define the format of the time component of the result string.
"F" (完整日期/長時間; 標準格式字串)"F" (full date / long time; standard format string) LongDatePattern,用來定義結果字串的日期元件格式。LongDatePattern, to define the format of the date component of the result string.

LongTimePattern,用來定義結果字串的時間元件格式。LongTimePattern, to define the format of the time component of the result string.
"g" (一般日期/短時間; 標準格式字串)"g" (general date / short time; standard format string) ShortDatePattern,用來定義結果字串的日期元件格式。ShortDatePattern, to define the format of the date component of the result string.

ShortTimePattern,用來定義結果字串的時間元件格式。ShortTimePattern, to define the format of the time component of the result string.
"G" (一般日期/完整時間; 標準格式字串)"G" (general date / long time; standard format string) ShortDatePattern,用來定義結果字串的日期元件格式。ShortDatePattern, to define the format of the date component of the result string.

LongTimePattern,用來定義結果字串的時間元件格式。LongTimePattern, to define the format of the time component of the result string.
"M"、"m" (月/日、標準格式字串)"M", "m" (month/day; standard format string) MonthDayPattern,用來定義結果字串的整體格式。MonthDayPattern, to define the overall format of the result string.
"O"、"o" (來回日期/時間、標準格式字串)"O", "o" (round-trip date/time; standard format string) 無。None.
"R"、"r" (RFC1123; 標準格式字串)"R", "r" (RFC1123; standard format string) RFC1123Pattern,用來定義符合 RFC 1123 標準的結果字串。RFC1123Pattern, to define a result string that conforms to the RFC 1123 standard. 屬性是唯讀。The property is read-only.
"s" (可排序日期/時間; 標準格式字串)"s" (sortable date/time; standard format string) SortableDateTimePattern,用來定義符合 ISO 8601 標準的結果字串。SortableDateTimePattern, to define a result string that conforms to the ISO 8601 standard. 屬性是唯讀。The property is read-only.
"t" (短時間; 標準格式字串)"t" (short time; standard format string) ShortTimePattern,用來定義結果字串的整體格式。ShortTimePattern, to define the overall format of the result string.
"T" (完整時間; 標準格式字串)"T" (long time; standard format string) LongTimePattern,用來定義結果字串的整體格式。LongTimePattern, to define the overall format of the result string.
"u" (通用可排序日期/時間; 標準格式字串)"u" (universal sortable date/time; standard format string) UniversalSortableDateTimePattern,用來定義符合國際標準時間 ISO 8601 標準的結果字串。UniversalSortableDateTimePattern, to define a result string that conforms to the ISO 8601 standard for coordinated universal time. 屬性是唯讀。The property is read-only.
"U" (通用完整日期/時間; 標準格式字串)"U" (universal full date/time; standard format string) FullDateTimePattern,用來定義結果字串的整體格式。FullDateTimePattern, to define the overall format of the result string.
"Y"、"y" (年月份、標準格式字串)"Y", "y" (year month; standard format string) YearMonthPattern,用來定義結果字串的整體格式。YearMonthPattern, to define the overall format of the result string.
"ddd" (自訂格式規範)"ddd" (custom format specifier) AbbreviatedDayNames,包含結果字串中一周的縮寫名稱。AbbreviatedDayNames, to include the abbreviated name of the day of the week in the result string.
"g"、"gg" (自訂格式規範)"g", "gg" (custom format specifier) GetEraName呼叫方法,以在結果字串中插入紀元名稱。Calls the GetEraName method to insert the era name in the result string.
"MMM" (自訂格式規範)"MMM" (custom format specifier) AbbreviatedMonthNames,將縮寫的月份名稱包含在結果字串中。AbbreviatedMonthNames, to include the abbreviated month name in the result string.
"MMMM" (自訂格式規範)"MMMM" (custom format specifier) MonthNames或者MonthGenitiveNames,若要在結果字串中包含完整的月份名稱。MonthNames or MonthGenitiveNames, to include the full month name in the result string.
"t" (自訂格式規範)"t" (custom format specifier) AMDesignator或者PMDesignator,若要在結果字串中包含 AM/PM 指示項的第一個字元。AMDesignator or PMDesignator, to include the first character of the AM/PM designator in the result string.
"tt" (自訂格式規範)"tt" (custom format specifier) AMDesignator或者PMDesignator,若要在結果字串中包含完整的 AM/PM 指示項。AMDesignator or PMDesignator, to include the full AM/PM designator in the result string.
":" (自訂格式規範)":" (custom format specifier) TimeSeparator,將時間分隔符號包含在結果字串中。TimeSeparator, to include the time separator in the result string.
"/" (自訂格式規範)"/" (custom format specifier) DateSeparator,以在結果字串中包含日期分隔符號。DateSeparator, to include the date separator in the result string.

修改 DateTimeFormatInfo 屬性Modifying DateTimeFormatInfo properties

您可以藉由修改可寫入DateTimeFormatInfo物件的相關聯屬性,來變更日期和時間格式字串所產生的結果字串。You can change the result string produced by date and time format strings by modifying the associated properties of a writable DateTimeFormatInfo object. 若要判斷DateTimeFormatInfo物件是否為可寫入,請IsReadOnly使用屬性。To determine if a DateTimeFormatInfo object is writable, use the IsReadOnly property. 若要以DateTimeFormatInfo這種方式自訂物件:To customize a DateTimeFormatInfo object in this way:

  1. 建立您想要修改其格式化慣例DateTimeFormatInfo之物件的讀取/寫入複本。Create a read/write copy of a DateTimeFormatInfo object whose formatting conventions you want to modify. (請參閱將DateTimeFormatInfo 物件具現化一節)。(See the Instantiating a DateTimeFormatInfo object section.)

  2. 修改用來產生所需結果字串的屬性或屬性。Modify the property or properties that are used to produce the desired result string. (如需格式化方法如何使用DateTimeFormatInfo屬性來定義結果字串的詳細資訊,請參閱上一節:格式字串和 DateTimeFormatInfo 屬性)。(For information about how formatting methods use DateTimeFormatInfo properties to define result strings, see the previous section, Format strings and DateTimeFormatInfo properties.)

  3. 在對格式化DateTimeFormatInfo方法的呼叫中, IFormatProvider使用您建立的自訂物件做為引數。Use the custom DateTimeFormatInfo object you created as the IFormatProvider argument in calls to formatting methods.

有兩種其他方式可變更結果字串的格式:There are two other ways to change the format of a result string:

  • 您可以使用CultureAndRegionInfoBuilder類別來定義自訂文化特性(具有唯一名稱,並補充現有文化特性的文化特性)或取代文化特性(使用,而不是特定文化特性)。You can use the CultureAndRegionInfoBuilder class to define either a custom culture (a culture that has a unique name and that supplements existing cultures) or a replacement culture (one that is used instead of a specific culture). 您可以用程式設計方式儲存和存取此文化特性CultureInfo ,就像 .NET Framework 所支援的任何物件一樣。You can save and access this culture programmatically as you would any CultureInfo object supported by the .NET Framework.

  • 如果結果字串不區分文化特性,且未遵循預先定義的格式,您可以使用自訂日期和時間格式字串。If the result string is not culture-sensitive and doesn't follow a predefined format, you can use a custom date and time format string. 例如,如果您要以 yyyymmddhhmmss.ffffff 格式序列化日期和時間資料,可以藉由將自訂格式字串傳遞給DateTime.ToString(String)方法來產生結果字串,而且您可以呼叫,將結果字串轉換回值DateTimeDateTime.ParseExact方法。For example, if you are serializing date and time data in the format YYYYMMDDHHmmss, you can generate the result string by passing the custom format string to the DateTime.ToString(String) method, and you can convert the result string back to a DateTime value by calling the DateTime.ParseExact method.

變更簡短日期模式Changing the short date pattern

下列範例會變更 "d" (簡短日期)標準格式字串所產生之結果字串的格式。The following example changes the format of a result string produced by the "d" (short date) standard format string. 它會將 en-us ShortDatePattern或英文(美國)文化特性的相關聯屬性從預設值 "M/d/yyyy" 變更為 "yyyy '-" MM "-" dd ",並使用" d "標準格式字串來顯示ShortDatePattern屬性之前和之後的日期變更.It changes the associated ShortDatePattern property for the en-US or English (United States) culture from its default of "M/d/yyyy" to "yyyy'-"MM"-"dd" and uses the "d" standard format string to display the date both before and after the ShortDatePattern property is changed.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      DateTime dateValue = new DateTime(2013, 8, 18); 
      CultureInfo enUS = CultureInfo.CreateSpecificCulture("en-US");
      DateTimeFormatInfo dtfi = enUS.DateTimeFormat;
      
      Console.WriteLine("Before modifying DateTimeFormatInfo object: ");
      Console.WriteLine("{0}: {1}\n", dtfi.ShortDatePattern, 
                                    dateValue.ToString("d", enUS));

      // Modify the short date pattern.
      dtfi.ShortDatePattern = "yyyy-MM-dd";
      Console.WriteLine("After modifying DateTimeFormatInfo object: ");
      Console.WriteLine("{0}: {1}", dtfi.ShortDatePattern, 
                                    dateValue.ToString("d", enUS));
   }
}
// The example displays the following output:
//       Before modifying DateTimeFormatInfo object:
//       M/d/yyyy: 8/18/2013
//       
//       After modifying DateTimeFormatInfo object:
//       yyyy-MM-dd: 2013-08-18
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim dateValue As New Date(2013, 08, 18) 
      Dim enUS As CultureInfo = CultureInfo.CreateSpecificCulture("en-US")
      Dim dtfi As DateTimeFormatInfo = enUS.DateTimeFormat
      
      Console.WriteLine("Before modifying DateTimeFormatInfo object: ")
      Console.WriteLine("{0}: {1}", dtfi.ShortDatePattern, 
                                    dateValue.ToString("d", enUS))
      Console.WriteLine()
      
      ' Modify the short date pattern.
      dtfi.ShortDatePattern = "yyyy-MM-dd"
      Console.WriteLine("After modifying DateTimeFormatInfo object: ")
      Console.WriteLine("{0}: {1}", dtfi.ShortDatePattern, 
                                    dateValue.ToString("d", enUS))
   End Sub
End Module
' The example displays the following output:
'       Before modifying DateTimeFormatInfo object:
'       M/d/yyyy: 8/18/2013
'       
'       After modifying DateTimeFormatInfo object:
'       yyyy-MM-dd: 2013-08-18

變更日期分隔字元Changing the date separator character

下列範例會變更DateTimeFormatInfo物件中表示 fr-fr 文化特性之格式設定慣例的日期分隔符號。The following example changes the date separator character in a DateTimeFormatInfo object that represents the formatting conventions of the fr-FR culture. 這個範例會使用 "g" 標準格式字串來顯示變更DateSeparator屬性前後的日期。The example uses the "g" standard format string to display the date both before and after the DateSeparator property is changed.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      DateTime dateValue = new DateTime(2013, 08, 28); 
      CultureInfo frFR = CultureInfo.CreateSpecificCulture("fr-FR");
      DateTimeFormatInfo dtfi = frFR.DateTimeFormat;
      
      Console.WriteLine("Before modifying DateSeparator property: {0}",
                        dateValue.ToString("g", frFR));
      
      // Modify the date separator.
      dtfi.DateSeparator = "-";
      Console.WriteLine("After modifying the DateSeparator property: {0}",
                        dateValue.ToString("g", frFR));
   }
}
// The example displays the following output:
//       Before modifying DateSeparator property: 18/08/2013 00:00
//       After modifying the DateSeparator property: 18-08-2013 00:00
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim dateValue As New Date(2013, 08, 28) 
      Dim frFR As CultureInfo = CultureInfo.CreateSpecificCulture("fr-FR")
      Dim dtfi As DateTimeFormatInfo = frFR.DateTimeFormat
      
      Console.WriteLine("Before modifying DateSeparator property: {0}",
                        dateValue.ToString("g", frFR))
      
      ' Modify the date separator.
      dtfi.DateSeparator = "-"
      Console.WriteLine("After modifying the DateSeparator property: {0}",
                        dateValue.ToString("g", frFR))
   End Sub
End Module
' The example displays the following output:
'       Before modifying DateSeparator property: 28/08/2013 00:00
'       After modifying the DateSeparator property: 28-08-2013 00:00

變更日期名稱縮寫和完整日期模式Changing day name abbreviations and the long date pattern

在某些情況下,完整的日期模式通常會顯示全天和月的名稱,以及月份日期和年份的數位,可能會太長。In some cases, the long date pattern, which typically displays the full day and month name along with the number of the day of the month and the year, may be too long. 下列範例會縮短 en-us 文化特性的完整日期模式,以傳回一或兩個字元的日名稱縮寫,後面接著日號、月份名稱縮寫和年份。The following example shortens the long date pattern for the en-US culture to return a one-character or two-character day name abbreviation followed by the day number, the month name abbreviation, and the year. 其執行方式是將較短的AbbreviatedDayNames日期名稱縮寫指派給陣列,以及修改指派LongDatePattern給屬性的自訂格式字串。It does this by assigning shorter day name abbreviations to the AbbreviatedDayNames array, and by modifying the custom format string assigned to the LongDatePattern property. 這會影響 "D" 和 "f" 標準格式字串所傳回的結果字串。This affects the result strings returned by the "D" and "f" standard format strings.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      DateTime value = new DateTime(2013, 7, 9);
      CultureInfo enUS = CultureInfo.CreateSpecificCulture("en-US");
      DateTimeFormatInfo dtfi = enUS.DateTimeFormat;
      String[] formats = { "D", "F", "f" };

      // Display date before modifying properties.
      foreach (var fmt in formats)
         Console.WriteLine("{0}: {1}", fmt, value.ToString(fmt, dtfi));

      Console.WriteLine();
      
      // We don't want to change the FullDateTimePattern, so we need to save it.
      String originalFullDateTimePattern = dtfi.FullDateTimePattern;
      
      // Modify day name abbreviations and long date pattern.
      dtfi.AbbreviatedDayNames = new String[] { "Su", "M", "Tu", "W", "Th", "F", "Sa" };
      dtfi.LongDatePattern = "ddd dd-MMM-yyyy";
      dtfi.FullDateTimePattern = originalFullDateTimePattern;
      foreach (var fmt in formats)
         Console.WriteLine("{0}: {1}", fmt, value.ToString(fmt, dtfi));

   }
}
// The example displays the following output:
//       D: Tuesday, July 09, 2013
//       F: Tuesday, July 09, 2013 12:00:00 AM
//       f: Tuesday, July 09, 2013 12:00 AM
//       
//       D: Tu 09-Jul-2013
//       F: Tuesday, July 09, 2013 12:00:00 AM
//       f: Tu 09-Jul-2013 12:00 AM
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim value As New Date(2013, 7, 9)
      Dim enUS As CultureInfo = CultureInfo.CreateSpecificCulture("en-US")
      Dim dtfi As DateTimeFormatInfo = enUS.DateTimeFormat
      Dim formats() As String = { "D", "F", "f" }

      ' Display date before modifying properties.
      For Each fmt In formats
         Console.WriteLine("{0}: {1}", fmt, value.ToString(fmt, dtfi))
      Next
      Console.WriteLine()
      
      ' We don't want to change the FullDateTimePattern, so we need to save it.
      Dim originalFullDateTimePattern As String = dtfi.FullDateTimePattern
      
      ' Modify day name abbreviations and long date pattern.
      dtfi.AbbreviatedDayNames = { "Su", "M", "Tu", "W", "Th", "F", "Sa" }
      dtfi.LongDatePattern = "ddd dd-MMM-yyyy"
      dtfi.FullDateTimePattern = originalFullDateTimePattern
      For Each fmt In formats
         Console.WriteLine("{0}: {1}", fmt, value.ToString(fmt, dtfi))
      Next
   End Sub
End Module
' The example displays the following output:
'       D: Tuesday, July 09, 2013
'       F: Tuesday, July 09, 2013 12:00:00 AM
'       f: Tuesday, July 09, 2013 12:00 AM
'       
'       D: Tu 09-Jul-2013
'       F: Tuesday, July 09, 2013 12:00:00 AM
'       f: Tu 09-Jul-2013 12:00 AM

一般來說, LongDatePattern屬性的變更也FullDateTimePattern會影響屬性,而後者則會定義 "F" 標準格式字串所傳回的結果字串。Ordinarily, the change to the LongDatePattern property also affects the FullDateTimePattern property, which in turn defines the result string returned by the "F" standard format string. 為了保留原始的完整日期和時間模式,此範例會重新指派在FullDateTimePattern LongDatePattern屬性修改後指派給屬性的原始自訂格式字串。To preserve the original full date and time pattern, the example reassigns the original custom format string assigned to the FullDateTimePattern property after the LongDatePattern property is modified.

從12小時制變更為24小時制Changing from a 12-hour clock to a 24-hour clock

對於 .NET Framework 中的許多文化特性而言,會使用12小時制和 AM/PM 指示項來表示時間。For many cultures in the .NET Framework, the time is expressed by using a 12-hour clock and an AM/PM designator. 下列範例所定義的ReplaceWith24HourClock方法,會以使用24小時制的格式,取代使用12小時制的任何時間格式。The following example defines a ReplaceWith24HourClock method that replaces any time format that uses a 12-hour clock with a format that uses a 24-hour clock.

using System;
using System.Globalization;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      CultureInfo enUS = CultureInfo.CreateSpecificCulture("en-US");
      DateTimeFormatInfo dtfi = enUS.DateTimeFormat;

      Console.WriteLine("Original Property Values:");
      Console.WriteLine("ShortTimePattern: " + dtfi.ShortTimePattern);
      Console.WriteLine("LongTimePattern: " + dtfi.LongTimePattern);
      Console.WriteLine("FullDateTimePattern: " + dtfi.FullDateTimePattern);
      Console.WriteLine();
      
      dtfi.LongTimePattern = ReplaceWith24HourClock(dtfi.LongTimePattern);
      dtfi.ShortTimePattern = ReplaceWith24HourClock(dtfi.ShortTimePattern);
      
      Console.WriteLine("Modififed Property Values:");
      Console.WriteLine("ShortTimePattern: " + dtfi.ShortTimePattern);
      Console.WriteLine("LongTimePattern: " + dtfi.LongTimePattern);
      Console.WriteLine("FullDateTimePattern: " + dtfi.FullDateTimePattern);
   }     
   
   private static string ReplaceWith24HourClock(string fmt)
   {
      string pattern = @"^(?<openAMPM>\s*t+\s*)? " +
                       @"(?(openAMPM) h+(?<nonHours>[^ht]+)$ " +
                       @"| \s*h+(?<nonHours>[^ht]+)\s*t+)";
      return Regex.Replace(fmt, pattern, "HH${nonHours}", 
                           RegexOptions.IgnorePatternWhitespace);   
   }
}
// The example displays the following output:
//       Original Property Values:
//       ShortTimePattern: h:mm tt
//       LongTimePattern: h:mm:ss tt
//       FullDateTimePattern: dddd, MMMM dd, yyyy h:mm:ss tt
//       
//       Modififed Property Values:
//       ShortTimePattern: HH:mm
//       LongTimePattern: HH:mm:ss
//       FullDateTimePattern: dddd, MMMM dd, yyyy HH:mm:ss
Imports System.Globalization
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim enUS As CultureInfo = CultureInfo.CreateSpecificCulture("en-US")
      Dim dtfi As DateTimeFormatInfo = enUS.DateTimeFormat

      Console.WriteLine("Original Property Values:")
      Console.WriteLine("ShortTimePattern: " + dtfi.ShortTimePattern)
      Console.WriteLine("LongTimePattern: " + dtfi.LongTimePattern)
      Console.WriteLine("FullDateTimePattern: " + dtfi.FullDateTimePattern)
      Console.WriteLine()
      
      dtfi.LongTimePattern = ReplaceWith24HourClock(dtfi.LongTimePattern)
      dtfi.ShortTimePattern = ReplaceWith24HourClock(dtfi.ShortTimePattern)
      
      Console.WriteLine("Modififed Property Values:")
      Console.WriteLine("ShortTimePattern: " + dtfi.ShortTimePattern)
      Console.WriteLine("LongTimePattern: " + dtfi.LongTimePattern)
      Console.WriteLine("FullDateTimePattern: " + dtfi.FullDateTimePattern)
   End Sub
   
   Private Function ReplaceWith24HourClock(fmt As String) As String
      Dim pattern As String = "^(?<openAMPM>\s*t+\s*)? " +
                              "(?(openAMPM) h+(?<nonHours>[^ht]+)$ " +
                              "| \s*h+(?<nonHours>[^ht]+)\s*t+)"
      Return Regex.Replace(fmt, pattern, "HH${nonHours}", RegexOptions.IgnorePatternWhitespace)   
   End Function
End Module
' The example displays the following output:
'       Original Property Values:
'       ShortTimePattern: h:mm tt
'       LongTimePattern: h:mm:ss tt
'       FullDateTimePattern: dddd, MMMM dd, yyyy h:mm:ss tt
'       
'       Modififed Property Values:
'       ShortTimePattern: HH:mm
'       LongTimePattern: HH:mm:ss
'       FullDateTimePattern: dddd, MMMM dd, yyyy HH:mm:ss

此範例會使用正則運算式來修改格式字串。The example uses a regular expression to modify the format string. 正則運算式模式@"^(?<openAMPM>\s*t+\s*)? (?(openAMPM) h+(?<nonHours>[^ht]+)$ | \s*h+(?<nonHours>[^ht]+)\s*t+)的定義如下:The regular expression pattern @"^(?<openAMPM>\s*t+\s*)? (?(openAMPM) h+(?<nonHours>[^ht]+)$ | \s*h+(?<nonHours>[^ht]+)\s*t+) is defined as follows:

模式Pattern 說明Description
^ 從字串的開頭開始比對。Begin the match at the beginning of the string.
(?<openAMPM>\s*t+\s*)? 比對零或一次零或多個空白字元,後面加上字母 "t" 一或多次,後面接著零個或多個空白字元。Match zero or one occurrence of zero or more white-space characters, followed by the letter "t" one or more times, followed by zero or more white-space characters. 此捕捉群組的名稱openAMPM為。This capturing group is named openAMPM.
(?(openAMPM) h+(?<nonHours>[^ht]+)$ openAMPM如果群組具有相符項,請比對字母 "h" 一或多次,後面接著一或多個不是 "h" 或 "t" 的字元。If the openAMPM group has a match, match the letter "h" one or more times, followed by one or more characters that are neither "h" nor "t". 比對會在字串結尾結束。The match ends at the end of the string. 在 "h" 之後所捕捉到的所有字元都會包含在nonHours名為的「捕捉群組」中。All characters captured after "h" are included in a capturing group named nonHours.
&#124; \s*h+(?<nonHours>[^ht]+)\s*t+) openAMPM如果群組沒有相符的,請比對字母 "h" 一或多次,後面接著一個或多個不是 "h" 或 "t" 的字元,後面接著零個或多個空白字元。If the openAMPM group does not have a match, match the letter "h" one or more times, followed by one or more characters that are neither "h" nor "t", followed by zero or more white-space characters. 最後,比對出現一或多次的字母 "t"。Finally, match one or more occurrences of the letter "t". 在 "h" 之後、空白字元和 "t" 之前所捕捉到的所有字元,都會包含在名為nonHours的「捕捉群組」中。All characters captured after "h" and before the white-spaces and "t" are included in a capturing group named nonHours.

nonHours捕捉群組包含自訂日期和時間格式字串的分鐘數,以及任何時間分隔符號的第二個元件。The nonHours capturing group contains the minute and possibly the second component of a custom date and time format string, along with any time separator symbols. 取代模式HH${nonHours}會將子字串 "HH" 加到這些元素前面。The replacement pattern HH${nonHours} prepends the substring "HH" to these elements.

顯示和變更日期中的紀元Displaying and changing the era in a date

下列範例會將 "g" 自訂格式規範新增至LongDatePattern物件的屬性,以表示 en-us 文化特性的格式設定慣例。The following example adds the "g" custom format specifier to the LongDatePattern property of an object that represents the formatting conventions of the en-US culture. 這項新增動作會影響下列三個標準格式字串:This addition affects the following three standard format strings:

  • "D" (完整日期)標準格式字串,它會直接對應至LongDatePattern屬性。The "D" (long date) standard format string, which maps directly to the LongDatePattern property.

  • "F" (完整日期/短時間)標準格式字串,它會產生會串連LongDatePatternShortTimePattern屬性所產生之子字串的結果字串。The "f" (full date / short time) standard format string, which produces a result string that concatenates the substrings produced by the LongDatePattern and ShortTimePattern properties.

  • "F" (完整日期/長時間)標準格式字串,它會直接對應至FullDateTimePattern屬性。The "F" (full date / long time) standard format string, which maps directly to the FullDateTimePattern property. 因為我們尚未明確設定此屬性值,所以會串連LongDatePatternLongTimePattern屬性以動態方式產生。Because we have not explicitly set this property value, it is generated dynamically by concatenating the LongDatePattern and LongTimePattern properties.

此範例也會示範如何變更其行事曆具有單一紀元之文化特性的紀元名稱。The example also shows how to change the era name for a culture whose calendar has a single era. 在此情況下,en-us 文化特性會使用西曆(以GregorianCalendar物件表示)。In this case, the en-US culture uses the Gregorian calendar, which is represented by a GregorianCalendar object. GregorianCalendar類別支援單一紀元,其名稱為西元The GregorianCalendar class supports a single era, which it names A.D. (西元西元)。(Anno Domini). 此範例會將紀元名稱變更為西元The example changes the era name to C.E. (一般紀元),方法是以常值字串取代指派給FullDateTimePattern屬性的格式字串中的 "g" 自訂格式規範。(Common Era) by replacing the "g" custom format specifier in the format string assigned to the FullDateTimePattern property with a literal string. 使用常值字串是必要的,因為紀元名稱通常是由GetEraName方法從 .NET Framework 或 Windows 作業系統所提供的文化特性資料表中的私用資料傳回。The use of a literal string is necessary, because the era name is typically returned by the GetEraName method from private data in the culture tables supplied by either the .NET Framework or the Windows operating system.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      DateTime dateValue = new DateTime(2013, 5, 18, 13, 30, 0);
      String[] formats = { "D", "f", "F" };      
      
      CultureInfo enUS = CultureInfo.CreateSpecificCulture("en-US");
      DateTimeFormatInfo dtfi = enUS.DateTimeFormat;
      String originalLongDatePattern = dtfi.LongDatePattern;

      // Display the default form of three long date formats.
      foreach (var fmt in formats)
         Console.WriteLine(dateValue.ToString(fmt, dtfi));

      Console.WriteLine();
      
      // Modify the long date pattern.
      dtfi.LongDatePattern = originalLongDatePattern + " g";
      foreach (var fmt in formats)
         Console.WriteLine(dateValue.ToString(fmt, dtfi));

      Console.WriteLine();
      
      // Change A.D. to C.E. (for Common Era)
      dtfi.LongDatePattern = originalLongDatePattern + @" 'C.E.'";
      foreach (var fmt in formats)
         Console.WriteLine(dateValue.ToString(fmt, dtfi));

   }
}
// The example displays the following output:
//       Saturday, May 18, 2013
//       Saturday, May 18, 2013 1:30 PM
//       Saturday, May 18, 2013 1:30:00 PM
//       
//       Saturday, May 18, 2013 A.D.
//       Saturday, May 18, 2013 A.D. 1:30 PM
//       Saturday, May 18, 2013 A.D. 1:30:00 PM
//       
//       Saturday, May 18, 2013 C.E.
//       Saturday, May 18, 2013 C.E. 1:30 PM
//       Saturday, May 18, 2013 C.E. 1:30:00 PM
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim dateValue As New Date(2013, 5, 18, 13, 30, 0)
      Dim formats() As String = { "D", "f", "F" }      
      
      Dim enUS As CultureInfo = CultureInfo.CreateSpecificCulture("en-US")
      Dim dtfi As DateTimeFormatInfo = enUS.DateTimeFormat
      Dim originalLongDatePattern As String = dtfi.LongDatePattern

      ' Display the default form of three long date formats.
      For Each fmt In formats
         Console.WriteLine(dateValue.ToString(fmt, dtfi))
      Next
      Console.WriteLine()
      
      ' Modify the long date pattern.
      dtfi.LongDatePattern = originalLongDatePattern + " g"
      For Each fmt In formats
         Console.WriteLine(dateValue.ToString(fmt, dtfi))
      Next
      Console.WriteLine()
      
      ' Change A.D. to C.E. (for Common Era)
      dtfi.LongDatePattern = originalLongDatePattern + " 'C.E.'"
      For Each fmt In formats
         Console.WriteLine(dateValue.ToString(fmt, dtfi))
      Next
   End Sub
End Module
' The example displays the following output:
'       Saturday, May 18, 2013
'       Saturday, May 18, 2013 1:30 PM
'       Saturday, May 18, 2013 1:30:00 PM
'       
'       Saturday, May 18, 2013 A.D.
'       Saturday, May 18, 2013 A.D. 1:30 PM
'       Saturday, May 18, 2013 A.D. 1:30:00 PM
'       
'       Saturday, May 18, 2013 C.E.
'       Saturday, May 18, 2013 C.E. 1:30 PM
'       Saturday, May 18, 2013 C.E. 1:30:00 PM

剖析日期和時間字串Parsing date and time strings

剖析包含將日期和時間的字串表示轉換為DateTimeDateTimeOffset值。Parsing involves converting the string representation of a date and time to a DateTime or DateTimeOffset value. 這兩種類型都包括ParseTryParseParseExactTryParseExact方法,以支援剖析作業。Both of these types include the Parse, TryParse, ParseExact, and TryParseExact methods to support parsing operations. 和方法會轉換可以具有ParseExact各種格式TryParseExact的字串,而則需要字串具有已定義的格式或格式。 TryParse ParseThe Parse and TryParse methods convert a string that can have a variety of formats, whereas ParseExact and TryParseExact require that the string have a defined format or formats. 如果剖析作業失敗, ParseParseExact擲回TryParse false例外狀況,而和TryParseExact會傳回。If the parsing operation fails, Parse and ParseExact throw an exception, whereas TryParse and TryParseExact return false.

剖析方法會隱含或明確地使用DateTimeStyles列舉值,以決定哪些樣式元素(例如前置、尾端或內部空白字元)可出現在要剖析的字串中,以及如何解讀剖析的字串或任何遺失的要素.The parsing methods implicitly or explicitly use a DateTimeStyles enumeration value to determine which style elements (such as leading, trailing, or inner white space) can be present in the string to be parsed, and how to interpret the parsed string or any missing elements. 如果您在Parse呼叫或DateTimeStyles TryParse方法時未提供值,則預設值為DateTimeStyles.AllowWhiteSpaces,這是包含DateTimeStyles.AllowLeadingWhiteDateTimeStyles.AllowTrailingWhiteDateTimeStyles.AllowInnerWhite旗標的複合樣式。If you don't provide a DateTimeStyles value when you call the Parse or TryParse method, the default is DateTimeStyles.AllowWhiteSpaces, which is a composite style that includes the DateTimeStyles.AllowLeadingWhite, DateTimeStyles.AllowTrailingWhite, and DateTimeStyles.AllowInnerWhite flags. ParseExact對於和TryParseExact方法,預設值為DateTimeStyles.None; 輸入字串必須精確對應至特定的自訂日期和時間格式字串。For the ParseExact and TryParseExact methods, the default is DateTimeStyles.None; the input string must correspond precisely to a particular custom date and time format string.

剖析方法也會隱含或明確地使用DateTimeFormatInfo物件,以定義可在要剖析的字串中出現的特定符號和模式。The parsing methods also implicitly or explicitly use a DateTimeFormatInfo object that defines the specific symbols and patterns that can occur in the string to be parsed. 如果您未提供DateTimeFormatInfo物件DateTimeFormatInfo ,預設會使用目前線程文化特性的物件。If you don't provide a DateTimeFormatInfo object, the DateTimeFormatInfo object for the current thread culture is used by default. 如需剖析日期和時間字串的詳細資訊,請參閱個別剖析方法,例如DateTime.ParseDateTime.TryParseDateTimeOffset.ParseExactDateTimeOffset.TryParseExactFor more information about parsing date and time strings, see the individual parsing methods, such as DateTime.Parse, DateTime.TryParse, DateTimeOffset.ParseExact, and DateTimeOffset.TryParseExact.

下列範例說明剖析日期和時間字串的區分文化特性性質。The following example illustrates the culture-sensitive nature of parsing date and time strings. 它會嘗試使用 en-us、en-GB、fr-fr 和 wi-fi 文化特性的慣例來剖析兩個日期字串。It tries to parse two date strings by using the conventions of the en-US, en-GB, fr-FR, and fi-FI cultures. 在 en-us 文化FormatException特性中,以8/18/2014 轉譯的日期會在其他三種文化特性中擲回例外狀況,因為18會被視為月份數。The date that is interpreted as 8/18/2014 in the en-US culture throws a FormatException exception in the other three cultures because 18 is interpreted as the month number. 1/2/2015 會剖析為 en-us 文化特性中第一個月的第二天,但做為其餘文化特性中第二個月的第一天。1/2/2015 is parsed as the second day of the first month in the en-US culture, but as the first day of the second month in the remaining cultures.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string[] dateStrings = { "08/18/2014", "01/02/2015" };
      string[] cultureNames = { "en-US", "en-GB", "fr-FR", "fi-FI" };
      
      foreach (var cultureName in cultureNames) {
         CultureInfo culture = CultureInfo.CreateSpecificCulture(cultureName);
         Console.WriteLine("Parsing strings using the {0} culture.", 
                           culture.Name);
         foreach (var dateStr in dateStrings) {
            try {
               Console.WriteLine(String.Format(culture, 
                                 "   '{0}' --> {1:D}", dateStr, 
                                 DateTime.Parse(dateStr, culture)));
            }
            catch (FormatException) {
               Console.WriteLine("   Unable to parse '{0}'", dateStr);
            }
         }
      }
   }
}
// The example displays the following output:
//       Parsing strings using the en-US culture.
//          '08/18/2014' --> Monday, August 18, 2014
//          '01/02/2015' --> Friday, January 02, 2015
//       Parsing strings using the en-GB culture.
//          Unable to parse '08/18/2014'
//          '01/02/2015' --> 01 February 2015
//       Parsing strings using the fr-FR culture.
//          Unable to parse '08/18/2014'
//          '01/02/2015' --> dimanche 1 février 2015
//       Parsing strings using the fi-FI culture.
//          Unable to parse '08/18/2014'
//          '01/02/2015' --> 1. helmikuuta 2015
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim dateStrings() As String = { "08/18/2014", "01/02/2015" }
      Dim cultureNames() As String = { "en-US", "en-GB", "fr-FR", "fi-FI" }
      
      For Each cultureName In cultureNames
         Dim culture As CultureInfo = CultureInfo.CreateSpecificCulture(cultureName)
         Console.WriteLine("Parsing strings using the {0} culture.", 
                           culture.Name)
         For Each dateStr In dateStrings
            Try
               Console.WriteLine(String.Format(culture, 
                                 "   '{0}' --> {1:D}", dateStr, 
                                 DateTime.Parse(dateStr, culture)))
            Catch e As FormatException
               Console.WriteLine("   Unable to parse '{0}'", dateStr)
            End Try
         Next
      Next
   End Sub
End Module
' The example displays the following output:
'       Parsing strings using the en-US culture.
'          '08/18/2014' --> Monday, August 18, 2014
'          '01/02/2015' --> Friday, January 02, 2015
'       Parsing strings using the en-GB culture.
'          Unable to parse '08/18/2014'
'          '01/02/2015' --> 01 February 2015
'       Parsing strings using the fr-FR culture.
'          Unable to parse '08/18/2014'
'          '01/02/2015' --> dimanche 1 février 2015
'       Parsing strings using the fi-FI culture.
'          Unable to parse '08/18/2014'
'          '01/02/2015' --> 1. helmikuuta 2015

通常會剖析日期和時間字串,原因有兩個:Date and time strings are typically parsed for two reasons:

  • 將使用者輸入轉換成日期和時間值。To convert user input into a date and time value.

  • 若要來回行程日期和時間值,也就是將先前序列化為字串的日期和時間值還原序列化。To round-trip a date and time value; that is, to deserialize a date and time value that was previously serialized as a string.

下列各節會更詳細地討論這兩項作業。The following sections discuss these two operations in greater detail.

剖析使用者字串Parsing user strings

當您剖析使用者輸入的日期和時間字串時,您應該一律具現DateTimeFormatInfo化反映使用者文化設定的物件,包括使用者可能進行的任何自訂。When you parse date and time strings input by the user, you should always instantiate a DateTimeFormatInfo object that reflects the user's cultural settings, including any customizations the user may have made. 否則,日期和時間物件可能會有不正確的值。Otherwise, the date and time object may have incorrect values. 如需如何具現化DateTimeFormatInfo反映使用者文化特性自訂之物件的相關資訊,請參閱DateTimeFormatInfo 和動態資料一節。For information about how to instantiate a DateTimeFormatInfo object that reflects user cultural customizations, see the DateTimeFormatInfo and dynamic data section.

下列範例說明會反映使用者文化設定的剖析作業與不是其中一項的差異。The following example illustrates the difference between a parsing operation that reflects user cultural settings and one that does not. 在此情況下,預設的系統文化特性為 en-us,但使用者已使用 [控制台]、[區域] 和 [語言],將簡短日期模式從預設值 "M/d/yyyy" 變更為 "YY/MM/dd"。In this case, the default system culture is en-US, but the user has used Control Panel, Region and Language to change the short date pattern from its default of "M/d/yyyy" to "yy/MM/dd". 當使用者輸入反映使用者設定的字串,且該字串由DateTimeFormatInfo同時反映使用者設定(覆寫)的物件進行剖析時,剖析作業會傳回正確的結果。When the user enters a string that reflects user settings, and the string is parsed by a DateTimeFormatInfo object that also reflects user settings (overrides), the parsing operation returns a correct result. 不過,當字串由DateTimeFormatInfo反映標準 en-us 文化特性設定的物件進行剖析時,剖析方法FormatException會擲回例外狀況,因為它會將14解釋為月份的數位,而不是年份的最後兩個數字。However, when the string is parsed by a DateTimeFormatInfo object that reflects standard en-US cultural settings, the parsing method throws a FormatException exception because it interprets 14 as the number of the month, not the last two digits of the year.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string inputDate = "14/05/10";
      
      CultureInfo[] cultures = { CultureInfo.GetCultureInfo("en-US"), 
                                 CultureInfo.CreateSpecificCulture("en-US") };
      
      foreach (var culture in cultures) {
         try {
            Console.WriteLine("{0} culture reflects user overrides: {1}", 
                              culture.Name, culture.UseUserOverride);
            DateTime occasion = DateTime.Parse(inputDate, culture);
            Console.WriteLine("'{0}' --> {1}", inputDate, 
                              occasion.ToString("D", CultureInfo.InvariantCulture));
         }
         catch (FormatException) {
            Console.WriteLine("Unable to parse '{0}'", inputDate);                           
         }   
         Console.WriteLine();  
      }
   }
}
// The example displays the following output:
//       en-US culture reflects user overrides: False
//       Unable to parse '14/05/10'
//       
//       en-US culture reflects user overrides: True
//       '14/05/10' --> Saturday, 10 May 2014
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim inputDate As String = "14/05/10"
      
      Dim cultures() As CultureInfo = { CultureInfo.GetCultureInfo("en-US"), 
                                        CultureInfo.CreateSpecificCulture("en-US") }
      
      For Each culture In cultures
         Try
            Console.WriteLine("{0} culture reflects user overrides: {1}", 
                              culture.Name, culture.UseUserOverride)
            Dim occasion As DateTime = DateTime.Parse(inputDate, culture)
            Console.WriteLine("'{0}' --> {1}", inputDate, 
                              occasion.ToString("D", CultureInfo.InvariantCulture))
         Catch e As FormatException
            Console.WriteLine("Unable to parse '{0}'", inputDate)                           
         End Try   
         Console.WriteLine()  
      Next
   End Sub
End Module
' The example displays the following output:
'       en-US culture reflects user overrides: False
'       Unable to parse '14/05/10'
'       
'       en-US culture reflects user overrides: True
'       '14/05/10' --> Saturday, 10 May 2014

序列化和還原序列化日期和時間資料Serializing and deserializing date and time data

序列化的日期和時間資料應為來回行程;也就是說,所有序列化和還原序列化的值都應該相同。Serialized date and time data are expected to round-trip; that is, all serialized and deserialized values should be identical. 如果日期和時間值代表單一時間點,則已還原序列化的值應該代表相同的時間點,而不論其是否為其所在系統的文化特性或時區。If a date and time value represents a single moment in time, the deserialized value should represent the same moment in time regardless of the culture or time zone of the system on which it was restored. 若要成功地反復存取日期和時間資料,您必須使用InvariantInfo屬性所傳回之不因文化特性而異的慣例來產生和剖析資料。To round-trip date and time data successfully, you must use the conventions of the invariant culture, which is returned by the InvariantInfo property, to generate and parse the data. 格式設定和剖析作業絕對不應反映預設文化特性的慣例。The formatting and parsing operations should never reflect the conventions of the default culture. 如果您使用預設的文化特性設定,資料的可攜性會受到嚴格的限制;只有在其文化特性設定與序列化所在的執行緒相同的執行緒上,才能成功還原序列化。If you use default cultural settings, the portability of the data is strictly limited; it can be successfully deserialized only on a thread whose cultural-specific settings are identical to those of the thread on which it was serialized. 在某些情況下,這表示資料甚至無法在同一個系統上成功序列化和還原序列化。In some cases, this means that the data cannot even be successfully serialized and deserialized on the same system.

如果日期和時間值的時間元件很重要,則也應該將它轉換成 UTC,並使用 "o" 或 "r"標準格式字串進行序列化。If the time component of a date and time value is significant, it should also be converted to UTC and serialized by using the "o" or "r" standard format string. 接著,您可以呼叫剖析方法來還原時間資料,並將適當的格式字串連同不變的文化provider特性當做引數傳遞給它。The time data can then be restored by calling a parsing method and passing it the appropriate format string along with the invariant culture as the provider argument.

下列範例說明來回行程日期和時間值的程式。The following example illustrates the process of round-tripping a date and time value. 它會在觀察到美國的系統上序列化日期和時間太平洋時間,其目前文化特性為 en-us。It serializes a date and time on a system that observes U.S. Pacific time and whose current culture is en-US.

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

public class Example
{
   public static void Main()
   {
      StreamWriter sw = new StreamWriter(@".\DateData.dat");
      // Define a date and time to serialize.
      DateTime originalDate = new DateTime(2014, 08, 18, 08, 16, 35);
      // Display information on the date and time.
      Console.WriteLine("Date to serialize: {0:F}", originalDate);
      Console.WriteLine("Current Culture:   {0}", 
                        CultureInfo.CurrentCulture.Name);
      Console.WriteLine("Time Zone:         {0}", 
                        TimeZoneInfo.Local.DisplayName);
      // Convert the date value to UTC.
      DateTime utcDate = originalDate.ToUniversalTime();
      // Serialize the UTC value.
      sw.Write(utcDate.ToString("o", DateTimeFormatInfo.InvariantInfo));
      sw.Close();
   }
}
// The example displays the following output:
//       Date to serialize: Monday, August 18, 2014 8:16:35 AM
//       Current Culture:   en-US
//       Time Zone:         (UTC-08:00) Pacific Time (US & Canada)
Imports System.Globalization
Imports System.IO

Module Example
   Public Sub Main()
      Dim sw As New StreamWriter(".\DateData.dat")
      ' Define a date and time to serialize.
      Dim originalDate As New Date(2014, 08, 18, 08, 16, 35)
      ' Display information on the date and time.
      Console.WriteLine("Date to serialize: {0:F}", originalDate)
      Console.WriteLine("Current Culture:   {0}", 
                        CultureInfo.CurrentCulture.Name)
      Console.WriteLine("Time Zone:         {0}", 
                        TimeZoneInfo.Local.DisplayName)
      ' Convert the date value to UTC.
      Dim utcDate As Date = originalDate.ToUniversalTime()
      ' Serialize the UTC value.
      sw.Write(utcDate.ToString("o", DateTimeFormatInfo.InvariantInfo))
      sw.Close()
   End Sub
End Module
' The example displays the following output:
'       Date to serialize: Monday, August 18, 2014 8:16:35 AM
'       Current Culture:   en-US
'       Time Zone:         (UTC-08:00) Pacific Time (US & Canada)

它會將在布魯塞爾、哥本哈根、馬德里和巴黎時區的系統上的資料還原序列化,並將目前的文化特性設為 fr-fr。It deserializes the data on a system in the Brussels, Copenhagen, Madrid and Paris time zone and whose current culture is fr-FR. 還原的日期會比原始日期晚9小時,這會反映時區調整,從 UTC 後8小時到 UTC 之前的一小時。The restored date is nine hours later than the original date, which reflects the time zone adjustment from eight hours behind UTC to one hour ahead of UTC. 原始日期和還原日期都代表相同的時間點。Both the original date and the restored date represent the same moment in time.

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

public class Example
{
   public static void Main()
   {
      // Open the file and retrieve the date string.
      StreamReader sr = new StreamReader(@".\DateData.dat");             
      String dateValue = sr.ReadToEnd();
      
      // Parse the date.
      DateTime parsedDate = DateTime.ParseExact(dateValue, "o", 
                            DateTimeFormatInfo.InvariantInfo);
      // Convert it to local time.                             
      DateTime restoredDate = parsedDate.ToLocalTime();
      // Display information on the date and time.
      Console.WriteLine("Deserialized date: {0:F}", restoredDate);
      Console.WriteLine("Current Culture:   {0}", 
                        CultureInfo.CurrentCulture.Name);
      Console.WriteLine("Time Zone:         {0}", 
                        TimeZoneInfo.Local.DisplayName);
   }
}
// The example displays the following output:
//    Deserialized date: lundi 18 août 2014 17:16:35
//    Current Culture:   fr-FR
//    Time Zone:         (UTC+01:00) Brussels, Copenhagen, Madrid, Paris
Imports System.Globalization
Imports System.IO

Module Example
   Public Sub Main()
      ' Open the file and retrieve the date string.
      Dim sr As New StreamReader(".\DateData.dat")             
      Dim dateValue As String = sr.ReadToEnd()
      
      ' Parse the date.
      Dim parsedDate As Date = Date.ParseExact(dateValue, "o", 
                               DateTimeFormatInfo.InvariantInfo)
      ' Convert it to local time.                             
      Dim restoredDate As Date = parsedDate.ToLocalTime()
      ' Display information on the date and time.
      Console.WriteLine("Deserialized date: {0:F}", restoredDate)
      Console.WriteLine("Current Culture:   {0}", 
                        CultureInfo.CurrentCulture.Name)
      Console.WriteLine("Time Zone:         {0}", 
                        TimeZoneInfo.Local.DisplayName)
   End Sub
End Module
' The example displays the following output:
'    Deserialized date: lundi 18 août 2014 17:16:35
'    Current Culture:   fr-FR
'    Time Zone:         (UTC+01:00) Brussels, Copenhagen, Madrid, Paris

建構函式

DateTimeFormatInfo()

初始化與文化特性無關 (不因文化特性而異) 之 DateTimeFormatInfo 類別的可寫入新執行個體。Initializes a new writable instance of the DateTimeFormatInfo class that is culture-independent (invariant).

屬性

AbbreviatedDayNames

取得或設定包含特定文化特性之星期縮寫名稱的一維陣列 (型別為 String)。Gets or sets a one-dimensional array of type String containing the culture-specific abbreviated names of the days of the week.

AbbreviatedMonthGenitiveNames

取得或設定字串陣列,這個陣列包含與目前 DateTimeFormatInfo 物件關聯的縮寫月份名稱。Gets or sets a string array of abbreviated month names associated with the current DateTimeFormatInfo object.

AbbreviatedMonthNames

取得或設定包含特定文化特性之月份縮寫名稱的一維字串陣列。Gets or sets a one-dimensional string array that contains the culture-specific abbreviated names of the months.

AMDesignator

取得或設定 "ante meridiem" (正午以前) 小時的字串指示項。Gets or sets the string designator for hours that are "ante meridiem" (before noon).

Calendar

取得或設定目前文化特性所使用的曆法。Gets or sets the calendar to use for the current culture.

CalendarWeekRule

取得或設定數值,指定要使用哪一個規則 (Rule) 來決定一年中的第一個日曆週。Gets or sets a value that specifies which rule is used to determine the first calendar week of the year.

CurrentInfo

取得根據目前文化特性格式化值的唯讀 DateTimeFormatInfo 物件。Gets a read-only DateTimeFormatInfo object that formats values based on the current culture.

DateSeparator

取得或設定分隔日期組成部分 (即年、月和日) 的字串。Gets or sets the string that separates the components of a date, that is, the year, month, and day.

DayNames

取得或設定包含特定文化特性之星期完整名稱的一維字串陣列。Gets or sets a one-dimensional string array that contains the culture-specific full names of the days of the week.

FirstDayOfWeek

取得或設定週的第一天。Gets or sets the first day of the week.

FullDateTimePattern

取得或設定完整日期和時間值的自訂格式字串。Gets or sets the custom format string for a long date and long time value.

InvariantInfo

取得與文化特性無關 (非變異) 的預設唯讀 DateTimeFormatInfo 物件。Gets the default read-only DateTimeFormatInfo object that is culture-independent (invariant).

IsReadOnly

取得值,這個值表示 DateTimeFormatInfo 物件是否唯讀。Gets a value indicating whether the DateTimeFormatInfo object is read-only.

LongDatePattern

取得或設定完整日期值的自訂格式字串。Gets or sets the custom format string for a long date value.

LongTimePattern

取得或設定完整時間值的自訂格式字串。Gets or sets the custom format string for a long time value.

MonthDayPattern

取得或設定月份和日值的自訂格式字串。Gets or sets the custom format string for a month and day value.

MonthGenitiveNames

取得或設定字串陣列,這個陣列包含與目前 DateTimeFormatInfo 物件關聯的月份名稱。Gets or sets a string array of month names associated with the current DateTimeFormatInfo object.

MonthNames

取得或設定包含特定文化特性之月份完整名稱的一維陣列 (型別為 String)。Gets or sets a one-dimensional array of type String containing the culture-specific full names of the months.

NativeCalendarName

取得行事曆的原生 (Native) 名稱,這個行事曆與目前 DateTimeFormatInfo 物件關聯。Gets the native name of the calendar associated with the current DateTimeFormatInfo object.

PMDesignator

取得或設定 "post meridiem" (正午以後) 小時的字串指示項。Gets or sets the string designator for hours that are "post meridiem" (after noon).

RFC1123Pattern

取得時間值的自訂格式字串,這個字串是根據網際網路工程任務推動小組 (Internet Engineering Task Force,IETF) 要求建議 (RFC) 1123 規格。Gets the custom format string for a time value that is based on the Internet Engineering Task Force (IETF) Request for Comments (RFC) 1123 specification.

ShortDatePattern

取得或設定簡短日期值的自訂格式字串。Gets or sets the custom format string for a short date value.

ShortestDayNames

取得或設定字串陣列,這個陣列包含與目前 DateTimeFormatInfo 物件關聯的最短唯一縮寫日名稱。Gets or sets a string array of the shortest unique abbreviated day names associated with the current DateTimeFormatInfo object.

ShortTimePattern

取得或設定簡短時間值的自訂格式字串。Gets or sets the custom format string for a short time value.

SortableDateTimePattern

取得可排序日期和時間值的自訂格式字串。Gets the custom format string for a sortable date and time value.

TimeSeparator

取得或設定分隔時間組成部分 (即時、分和秒) 的字串。Gets or sets the string that separates the components of time, that is, the hour, minutes, and seconds.

UniversalSortableDateTimePattern

取得自訂格式字串,以取得由 ISO 8601 所定義的國際標準、可排序日期和時間字串。Gets the custom format string for a universal, sortable date and time string, as defined by ISO 8601.

YearMonthPattern

取得或設定年月值的自訂格式字串。Gets or sets the custom format string for a year and month value.

方法

Clone()

建立 DateTimeFormatInfo 的淺層複本。Creates a shallow copy of the DateTimeFormatInfo.

Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(繼承來源 Object)
GetAbbreviatedDayName(DayOfWeek)

根據與目前 DateTimeFormatInfo 物件關聯的文化特性,傳回一星期內指定某一天的文化特性特有縮寫名稱。Returns the culture-specific abbreviated name of the specified day of the week based on the culture associated with the current DateTimeFormatInfo object.

GetAbbreviatedEraName(Int32)

如果縮寫存在的話,傳回含有指定紀元縮寫名稱的字串。Returns the string containing the abbreviated name of the specified era, if an abbreviation exists.

GetAbbreviatedMonthName(Int32)

根據與目前 DateTimeFormatInfo 物件關聯的文化特性,傳回指定月份的文化特性特有縮寫名稱。Returns the culture-specific abbreviated name of the specified month based on the culture associated with the current DateTimeFormatInfo object.

GetAllDateTimePatterns()

傳回可格式化日期和時間值的所有標準模式。Returns all the standard patterns in which date and time values can be formatted.

GetAllDateTimePatterns(Char)

傳回可以使用所指定標準格式字串來格式化日期和時間值的所有模式。Returns all the patterns in which date and time values can be formatted using the specified standard format string.

GetDayName(DayOfWeek)

根據與目前 DateTimeFormatInfo 物件關聯的文化特性,傳回一星期內指定某一天的文化特性特有完整名稱。Returns the culture-specific full name of the specified day of the week based on the culture associated with the current DateTimeFormatInfo object.

GetEra(String)

傳回表示指定紀元的整數。Returns the integer representing the specified era.

GetEraName(Int32)

傳回含有指定紀元名稱的字串。Returns the string containing the name of the specified era.

GetFormat(Type)

傳回指定的類型的物件,以提供日期和時間格式服務。Returns an object of the specified type that provides a date and time formatting service.

GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(繼承來源 Object)
GetInstance(IFormatProvider)

傳回與指定 DateTimeFormatInfo 關聯的 IFormatProvider 物件。Returns the DateTimeFormatInfo object associated with the specified IFormatProvider.

GetMonthName(Int32)

根據與目前 DateTimeFormatInfo 物件關聯的文化特性,傳回指定月份的文化特性特有完整名稱。Returns the culture-specific full name of the specified month based on the culture associated with the current DateTimeFormatInfo object.

GetShortestDayName(DayOfWeek)

為與目前 DateTimeFormatInfo 物件關聯的星期內指定的某一天,取得最短的縮寫日名稱。Obtains the shortest abbreviated day name for a specified day of the week associated with the current DateTimeFormatInfo object.

GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(繼承來源 Object)
ReadOnly(DateTimeFormatInfo)

傳回唯讀的 DateTimeFormatInfo 包裝函式。Returns a read-only DateTimeFormatInfo wrapper.

SetAllDateTimePatterns(String[], Char)

設定對應於指定之標準格式字串的自訂日期和時間格式字串。Sets the custom date and time format strings that correspond to a specified standard format string.

ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)

明確介面實作

ISerializable.GetObjectData(SerializationInfo, StreamingContext)

適用於

另請參閱