DateTimeFormatInfo 類別

定義

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

public ref class DateTimeFormatInfo sealed : IFormatProvider
public ref class DateTimeFormatInfo sealed : ICloneable, IFormatProvider
public ref class DateTimeFormatInfo sealed : ICloneable, IFormatProvider, System::Runtime::Serialization::ISerializable
public sealed class DateTimeFormatInfo : IFormatProvider
public sealed class DateTimeFormatInfo : ICloneable, IFormatProvider
[System.Serializable]
public sealed class DateTimeFormatInfo : ICloneable, IFormatProvider, System.Runtime.Serialization.ISerializable
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class DateTimeFormatInfo : ICloneable, IFormatProvider
type DateTimeFormatInfo = class
    interface IFormatProvider
type DateTimeFormatInfo = class
    interface ICloneable
    interface IFormatProvider
[<System.Serializable>]
type DateTimeFormatInfo = class
    interface ICloneable
    interface IFormatProvider
    interface ISerializable
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type DateTimeFormatInfo = class
    interface ICloneable
    interface IFormatProvider
Public NotInheritable Class DateTimeFormatInfo
Implements IFormatProvider
Public NotInheritable Class DateTimeFormatInfo
Implements ICloneable, IFormatProvider
Public NotInheritable Class DateTimeFormatInfo
Implements ICloneable, IFormatProvider, ISerializable
繼承
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 特性,並取得 DateTimeFormatInfo 其屬性傳回的物件,以抓取中性文化特性的物件 CultureInfo.DateTimeFormatIn 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. 下列範例說明將表示中性文化特性的物件具現化的方法 DateTimeFormatInfoThe 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 版中,嘗試取出 DateTimeFormatInfo 反映中性文化特性之格式慣例的物件會擲回例外狀況 NotSupportedExceptionIn the .NET Framework versions 1.0 through .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. DateTimeFormatInfo.NET Framework DateTimeFormatInfo 會傳回物件,以反映屬於中性文化特性之子系的特定文化特性的格式慣例,而不是使用泛型值來擴展物件。Instead 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-us 文化特性的格式化慣例,而 fr 文化特性的物件會 DateTimeFormatInfo 反映 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 ,並顯示其屬性的值 IsReadOnlyThe 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 是動態的,就像類別所提供的文化特性資料一樣 CultureInfoThe 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 與特定物件相關聯的物件,您不應該對其值的穩定性做出任何假設 CultureInfoYou 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. 發生這種情況時, DateTimeFormatInfo 屬性傳回的物件會 CurrentInfo 變更為與目前文化特性相關聯的物件。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. 如果 CultureInfo.UseUserOverride 屬性設定為,則 true DateTimeFormatInfo 也會從使用者設定中取出物件的屬性。If 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

DateTimeFormatInfo在所有日期和時間格式化作業中,隱含或明確使用物件。A 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介面包含單一方法 IFormatProvider.GetFormat(Type)The 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 格式化作業中,介面和類別之間的關聯性 DateTimeFormatInfoThe 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 和物件,以及 DateTimeFormatInfo ICustomFormatter 執行。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, 13, 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. 此外,資料表只會列出對應至屬性的自訂格式規範 DateTimeFormatInfoIn 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" (month/day;標準格式字串) "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" (year month;標準格式字串) "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

您可以藉由修改可寫入物件的相關聯屬性,來變更日期和時間格式字串所產生的結果字串 DateTimeFormatInfoYou 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). 您可以用程式設計方式儲存和存取此文化特性,就像 .NET Framework 所支援的任何 CultureInfo 物件一樣。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.ParseExactFor 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. 它會將 ShortDatePattern en-us 或英文 (美國) 文化特性的相關屬性,從其預設值 "M/d/yyyy" 變更為 "yyyy '-" MM "-" dd ",並使用" d "標準格式字串來顯示變更屬性之前和之後的日期 ShortDatePatternIt 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" 標準格式字串來顯示變更屬性前後的日期 DateSeparatorThe 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: 28/08/2013 00:00
//       After modifying the DateSeparator property: 28-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 文化特性的完整日期模式,以傳回一個字元或兩個字元的日名稱縮寫,後面接著 day、month name 縮寫和 year。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 陣列,以及修改指派給屬性的自訂格式字串,來執行這項工作 LongDatePatternIt 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 9, 2013
//       F: Tuesday, July 9, 2013 12:00:00 AM
//       f: Tuesday, July 9, 2013 12:00 AM
//
//       D: Tu 09-Jul-2013
//       F: Tuesday, July 9, 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 9, 2013
'       F: Tuesday, July 9, 2013 12:00:00 AM
'       f: Tuesday, July 9, 2013 12:00 AM
'
'       D: Tu 09-Jul-2013
'       F: Tuesday, July 9, 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 會在修改屬性之後,重新指派指派給屬性的原始自訂格式字串 LongDatePatternTo 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. 此捕獲群組的名稱為 openAMPMThis 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" 之後所捕捉的所有字元都會包含在名為的捕獲群組中 nonHoursAll 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" 之前捕捉的所有字元,都會包含在名為的捕獲群組中 nonHoursAll 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" (完整日期/短時間) 標準格式字串,此字串會產生串連和屬性所產生之子字串的結果字串 LongDatePattern ShortTimePatternThe "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. 因為我們並未明確設定此屬性值,所以會串連和屬性以動態方式 LongDatePattern 產生 LongTimePatternBecause 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 文化特性會使用西曆(以物件表示) GregorianCalendarIn 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. 使用常值字串,將指派給屬性的格式字串中的 "g" 自訂格式規範取代為 (的一般紀元) FullDateTimePattern(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. ParseTryParse 方法會轉換可以有各種格式的字串,而 ParseExact TryParseExact 要求字串必須有定義的格式或格式。The 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 TryParseExact falseIf 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. 如果您在 DateTimeStyles 呼叫或方法時未提供值 Parse TryParse ,則預設為 DateTimeStyles.AllowWhiteSpaces ,這是包含 DateTimeStyles.AllowLeadingWhiteDateTimeStyles.AllowTrailingWhite 和旗標的複合樣式 DateTimeStyles.AllowInnerWhiteIf 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. 針對 ParseExactTryParseExact 方法,預設值為 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-us、fr-fr 和 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 文化特性中解釋為8/18/2014 的日期會 FormatException 在其他三種文化特性中擲回例外狀況,因為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. 然後藉由呼叫剖析方法,並將適當的格式字串以及不因文化特性而異的文化特性傳遞至引數,來還原時間資料 providerThe 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 之後的八小時到 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 的淺層複製。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)

將序列化目標物件所需的資料填入 SerializationInfo 中。Populates a SerializationInfo with the data needed to serialize the target object.

適用於

另請參閱