DateTimeFormatInfo 类

定义

提供有关日期和时间值格式的区域性特定信息。Provides culture-specific information about the format of date and time values.

public ref class DateTimeFormatInfo sealed : ICloneable, IFormatProvider
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public sealed class DateTimeFormatInfo : ICloneable, IFormatProvider
type DateTimeFormatInfo = class
    interface ICloneable
    interface IFormatProvider
Public NotInheritable Class DateTimeFormatInfo
Implements ICloneable, IFormatProvider
继承
DateTimeFormatInfo
属性
实现

示例

下面的示例使用反射获取英语(美国)区域性DateTimeFormatInfo的对象的属性。The following example uses reflection to get the properties of the DateTimeFormatInfo object for the English (United States) culture. 它显示包含自定义格式字符串的属性的值,并使用这些字符串显示格式化日期。It displays the value of those properties that contain custom format strings and uses those strings to display formatted dates.

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

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

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

注解

DateTimeFormatInfo类的属性包含特定于区域性的信息,用于设置或分析日期和时间值,如下所示:The properties of the DateTimeFormatInfo class contain culture-specific information for formatting or parsing date and time values such as the following:

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

  • 用于格式化时间值的模式。The patterns used to format time values.

  • 一周中各天的名称。The names of the days of the week.

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

  • 上午The A.M. P.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 CA 则是表示加拿大所说英语的特定区域性。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.DateTimeFormat属性返回的对象。In addition, you can retrieve a neutral culture's DateTimeFormatInfo object by retrieving a neutral culture from a specific culture's CultureInfo.Parent property and retrieving the DateTimeFormatInfo object returned by its CultureInfo.DateTimeFormat property. 除非父区域性表示固定区域性,否则返回DateTimeFormatInfo的对象是可读/写的。Unless the parent culture represents the invariant culture, the returned DateTimeFormatInfo object is read/write. 下面的示例演示了实例化DateTimeFormatInfo表示非特定区域性的对象的方法。The following example illustrates these ways of instantiating a DateTimeFormatInfo object that represents a neutral culture.

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

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

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

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

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

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

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

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

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

备注

在 .NET Framework 版本1.0 到.NET Framework 3.5.NET Framework 3.5中,尝试DateTimeFormatInfo检索反映非特定区域性的格式设置约定的对象会引发NotSupportedException异常。In the .NET Framework versions 1.0 through .NET Framework 3.5.NET Framework 3.5, trying to retrieve a DateTimeFormatInfo object that reflects the formatting conventions of a neutral culture throws a NotSupportedException exception.

但是,非特定区域性缺少区域性特定的格式设置信息,因为它与特定的国家/地区无关。However, a neutral culture lacks culture-specific formatting information, because it is independent of a specific country/region. .NET Framework 返回一个DateTimeFormatInfo对象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 区域性的对象反映 en-us 区域性的格式设置约定, DateTimeFormatInfo fr 区域性的对象反映 fr-fr 区域性的格式设置约定。For example, the DateTimeFormatInfo object for the neutral en culture reflects the formatting conventions of the en-US culture, and the DateTimeFormatInfo object for the fr culture reflects the formatting conventions of the fr-FR culture.

您可以使用如下所示的代码来确定非特定区域性表示的特定区域性格式约定。You can use code like the following to determine which specific culture's formatting conventions a neutral culture represents. 该示例使用反射将非特定DateTimeFormatInfo区域性的属性与特定子区域性的属性进行比较。The example uses reflection to compare the DateTimeFormatInfo properties of a neutral culture with the properties of a specific child culture. 如果两个日历是相同的日历类型,则它会将两个日历视为等效,如果GregorianCalendar.CalendarType它们的属性具有相同的值,则为公历。It considers two calendars to be equivalent if they are the same calendar type and, for Gregorian calendars, if their GregorianCalendar.CalendarType properties have identical values.

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

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

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

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

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

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

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

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

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

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

实例化当前区域性的 DateTimeFormatInfo 对象Instantiating a DateTimeFormatInfo object for the current culture

可以通过以下方式DateTimeFormatInfo实例化表示当前区域性的格式设置约定的对象:You can instantiate a DateTimeFormatInfo object that represents the formatting conventions of the current culture in the following ways:

下面的示例使用每个方法来实例化DateTimeFormatInfo表示当前区域性的格式设置约定的对象。The following example uses each of these methods to instantiate a DateTimeFormatInfo object that represents the formatting conventions of the current culture. 然后,它指示对象是否为只读。It then indicates whether the object is read-only.

DateTimeFormatInfo dtfi;

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

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

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

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

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

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

可以通过以下方式之一DateTimeFormatInfo创建表示当前线程区域性约定的可写对象:You can create a writable DateTimeFormatInfo object that represents the conventions of the current thread culture in one of these ways:

下面的示例演示了实例化读/写DateTimeFormatInfo对象并显示其IsReadOnly属性的值的每个方法。The following example illustrates each way of instantiating a read/write DateTimeFormatInfo object and displays the value of its IsReadOnly property.

using System;
using System.Globalization;

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

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

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

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

在 Windows 中,用户可以通过 "控制面板" DateTimeFormatInfo中的 "区域和语言" 应用程序覆盖用于格式化和分析操作的某些属性值。In Windows, the user can override some of the DateTimeFormatInfo property values used in formatting and parsing operations through the Region and Language application in Control Panel. 例如,区域性为英语(美国)的用户可能会选择使用24小时制(格式为 HH: mm: ss)而不是默认的12小时制(格式为 h:mm: ss tt)来显示长时间值。For example, a user whose culture is English (United States) might choose to display long time values using a 24-hour clock (in the format HH:mm:ss) instead of the default 12-hour clock (in the format h:mm:ss tt). 前面DateTimeFormatInfo讨论的方法中检索的对象反映了这些用户覆盖。The DateTimeFormatInfo objects retrieved in the ways discussed previously all reflect these user overrides. 如果不需要这样做,则可以通过NumberFormatInfo CultureInfo.CultureInfo(String, Boolean)调用构造函数false并为useUserOverride参数提供值来创建不反映用户重写的对象(也可以是读/写而不是只读的)。If this is undesirable, you can create a NumberFormatInfo object that does not reflect user overrides (and is also read/write instead of read-only) by calling the CultureInfo.CultureInfo(String, Boolean) constructor and supplying a value of false for the useUserOverride argument. 下面的示例为当前区域性为英语(美国)并且其长时间模式已从默认值 h:mm: ss tt 改为 HH: mm: ss 的系统进行了说明。The following example illustrates this for a system whose current culture is English (United States) and whose long time pattern has been changed from the default of h:mm:ss tt to HH:mm:ss.

using System;
using System.Globalization;

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

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

DateTimeFormatInfo 和动态数据DateTimeFormatInfo and dynamic data

用于设置DateTimeFormatInfo类的日期和时间值格式的区域性特定数据是动态的,就像CultureInfo类提供的区域性数据一样。The culture-specific data for formatting date and time values provided by the DateTimeFormatInfo class is dynamic, just like cultural data provided by the CultureInfo class. 不应对与特定DateTimeFormatInfo CultureInfo对象关联的对象的值的稳定性做出任何假设。You should not make any assumptions about the stability of values for DateTimeFormatInfo objects that are associated with particular CultureInfo objects. 只有固定区域性提供的数据及其关联DateTimeFormatInfo的对象才是稳定的。Only the data provided by the invariant culture and its associated DateTimeFormatInfo object is stable. 其他数据可以在应用程序会话之间更改,也可以在应用程序运行时进行更改。Other data can change between application sessions or even while your application is running. 有四个主要的更改源:There are four major sources of change:

  • 系统更新。System updates. 区域性首选项(如首选日历或惯用日期和时间格式)会随时间而改变。Cultural preferences such as the preferred calendar or customary date and time formats change over time. 发生这种情况时,Windows 更新包括对DateTimeFormatInfo特定区域性的属性值的更改。When this happens, Windows Update includes changes to the DateTimeFormatInfo property value for a particular culture.

  • 替换区域性。Replacement cultures. CultureAndRegionInfoBuilder类可用于替换现有区域性的数据。The CultureAndRegionInfoBuilder class can be used to replace the data of an existing culture.

  • 对属性值进行级联更改。Cascading changes to property values. 许多与区域性相关的属性在运行时可能会更改,而这又会导致DateTimeFormatInfo数据更改。A number of culture-related properties can change at run time, which, in turn, causes DateTimeFormatInfo data to change. 例如,可以通过编程方式或通过用户操作更改当前区域性。For example, the current culture can be changed either programmatically or through user action. 发生这种情况时DateTimeFormatInfoCurrentInfo由属性返回的对象更改为与当前区域性关联的对象。When this happens, the DateTimeFormatInfo object returned by the CurrentInfo property changes to an object associated with the current culture. 同样,区域性的日历可以更改,这可能会导致对大量DateTimeFormatInfo属性值的更改。Similarly, a culture's calendar can change, which can result in changes to numerous DateTimeFormatInfo property values.

  • 用户首选项。User preferences. 应用程序的用户可以选择通过控制面板中的 "区域和语言选项" 覆盖与当前系统区域性关联的某些值。Users of your application might choose to override some of the values associated with the current system culture through the regional and language options in Control Panel. 例如,用户可以选择以不同的格式显示日期。For example, users might choose to display the date in a different format. 如果将true属性设置为DateTimeFormatInfo ,则还会从用户设置中检索对象的属性。 CultureInfo.UseUserOverrideIf the CultureInfo.UseUserOverride property is set to true, the properties of the DateTimeFormatInfo object is also retrieved from the user settings. 如果用户设置与CultureInfo对象关联的区域性不兼容(例如,如果所选日历不是OptionalCalendars属性指示的日历之一),则方法的结果和属性的值未定义。If the user settings are incompatible with the culture associated with the CultureInfo object (for example, if the selected calendar is not one of the calendars indicated by the OptionalCalendars property), the results of the methods and the values of the properties are undefined.

若要最大程度地减少数据不一致的可能性,则在DateTimeFormatInfo创建对象时,将初始化对象的所有用户可重写属性。To minimize the possibility of inconsistent data, all user-overridable properties of a DateTimeFormatInfo object are initialized when the object is created. 仍有可能存在不一致的情况,因为对象创建和用户重写进程都是原子的,相关值可以在对象创建期间更改。There is still a possibility of inconsistency, because neither object creation nor the user override process is atomic and the relevant values can change during object creation. 但是,这种情况应该非常罕见。However, this situation should be extremely rare.

您可以控制是否在表示与系统区域性DateTimeFormatInfo相同的区域性的对象中反映用户重写。You can control whether user overrides are reflected in DateTimeFormatInfo objects that represent the same culture as the system culture. 下表列出了可用于检索对象的DateTimeFormatInfo方法,并指示生成的对象是否反映用户覆盖。The following table lists the ways in which a DateTimeFormatInfo object can be retrieved and indicates whether the resulting object reflects user overrides.

CultureInfo 和 DateTimeFormatInfo 对象的源Source of CultureInfo and DateTimeFormatInfo object 反映用户替代Reflects user overrides
CultureInfo.CurrentCulture.DateTimeFormat 属性CultureInfo.CurrentCulture.DateTimeFormat property Yes
DateTimeFormatInfo.CurrentInfo 属性DateTimeFormatInfo.CurrentInfo property Yes
CultureInfo.CreateSpecificCulture 方法CultureInfo.CreateSpecificCulture method Yes
CultureInfo.GetCultureInfo 方法CultureInfo.GetCultureInfo method NoNo
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:

所有日期和时间格式化操作都利用了IFormatProvider实现。All date and time formatting operations make use of an IFormatProvider implementation. 接口包含一个方法,即IFormatProvider.GetFormat(Type)IFormatProviderThe IFormatProvider interface includes a single method, IFormatProvider.GetFormat(Type). 向此回调方法传递Type对象,该对象表示提供格式设置信息所需的类型。This callback method is passed a Type object that represents the type needed to provide formatting information. 方法返回该类型的实例,或者null如果无法提供该类型的实例,则返回。The method returns either an instance of that type or null if it cannot provide an instance of the type. .NET Framework 包含用于设置IFormatProvider日期和时间格式的两种实现:The .NET Framework includes two IFormatProvider implementations for formatting dates and times:

如果未向格式设置方法显式提供CultureInfo CultureInfo.CurrentCulture 实现,则使用表示当前线程区域性的属性IFormatProvider返回的对象。If an IFormatProvider implementation is not provided to a formatting method explicitly, the CultureInfo object returned by the CultureInfo.CurrentCulture property that represents the current thread culture is used.

下面的示例演示了在格式设置IFormatProvider操作中接口DateTimeFormatInfo和类之间的关系。The following example illustrates the relationship between the IFormatProvider interface and the DateTimeFormatInfo class in formatting operations. 它定义了一个IFormatProvider自定义GetFormat实现,该实现的方法显示格式设置操作所请求的对象的类型。It defines a custom IFormatProvider implementation whose GetFormat method displays the type of the object requested by the formatting operation. 如果它正在请求DateTimeFormatInfo对象,则该方法为当前线程区域性DateTimeFormatInfo提供对象。If it is requesting a DateTimeFormatInfo object, the method provides the DateTimeFormatInfo object for the current thread culture. 如示例的输出所示, Decimal.ToString(IFormatProvider)方法DateTimeFormatInfo请求对象提供String.Format(IFormatProvider, String, Object[])格式设置信息,而ICustomFormatter方法请求NumberFormatInfoDateTimeFormatInfo对象以及部署.As the output from the example shows, the Decimal.ToString(IFormatProvider) method requests a DateTimeFormatInfo object to provide formatting information, whereas the String.Format(IFormatProvider, String, Object[]) method requests NumberFormatInfo and DateTimeFormatInfo objects as well as an ICustomFormatter implementation.

using System;
using System.Globalization;

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

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

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

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

格式字符串和 DateTimeFormatInfo 属性Format strings and DateTimeFormatInfo properties

DateTimeFormatInfo对象包含在格式设置操作中使用日期和时间值的三种属性:The DateTimeFormatInfo object includes three kinds of properties that are used in formatting operations with date and time values:

标准日期和时间格式字符串(如 "d"、"d"、"f" 和 "f")是对应于特定DateTimeFormatInfo格式模式属性的别名。The standard date and time format strings, such as "d", "D", "f", and "F", are aliases that correspond to particular DateTimeFormatInfo format pattern properties. 大多数自定义日期和时间格式字符串与格式设置操作在结果流中插入的字符串或子字符串相关。Most of the custom date and time format strings are related to strings or substrings that a formatting operation inserts into the result stream. 下表列出了标准和自定义日期和时间格式说明符及其相关DateTimeFormatInfo属性。The following table lists the standard and custom date and time format specifiers and their associated DateTimeFormatInfo properties. 有关如何使用这些格式说明符的详细信息,请参阅标准日期和时间格式字符串自定义日期和时间格式字符串For details about how to use these format specifiers, see Standard Date and Time Format Strings and Custom Date and Time Format Strings. 请注意,每个标准格式字符串对应DateTimeFormatInfo于其值为自定义日期和时间格式字符串的属性。Note that each standard format string corresponds to a DateTimeFormatInfo property whose value is a custom date and time format string. 此自定义格式字符串中的各个说明符又与其他DateTimeFormatInfo属性相对应。The individual specifiers in this custom format string in turn correspond to other DateTimeFormatInfo properties. 此表仅DateTimeFormatInfo列出标准格式字符串为其别名的属性,并且不列出可由分配给这些别名属性的自定义格式字符串访问的属性。The table lists only the DateTimeFormatInfo properties for which the standard format strings are aliases, and does not list properties that may be accessed by custom format strings assigned to those aliased properties. 此外,此表仅列出对应于DateTimeFormatInfo属性的自定义格式说明符。In addition, the table lists only custom format specifiers that correspond to DateTimeFormatInfo properties.

格式说明符Format specifier 关联属性Associated properties
"d" (短日期; 标准格式字符串)"d" (short date; standard format string) ShortDatePattern,用于定义结果字符串的总体格式。ShortDatePattern, to define the overall format of the result string.
"D" (长日期:标准格式字符串)"D" (long date; standard format string) LongDatePattern,用于定义结果字符串的总体格式。LongDatePattern, to define the overall format of the result string.
"f" (完整日期/短时间; 标准格式字符串)"f" (full date / short time; standard format string) LongDatePattern,用于定义结果字符串中日期部分的格式。LongDatePattern, to define the format of the date component of the result string.

ShortTimePattern,用于定义结果字符串的时间部分的格式。ShortTimePattern, to define the format of the time component of the result string.
"F" (完整日期/长时间; 标准格式字符串)"F" (full date / long time; standard format string) LongDatePattern,用于定义结果字符串中日期部分的格式。LongDatePattern, to define the format of the date component of the result string.

LongTimePattern,用于定义结果字符串的时间部分的格式。LongTimePattern, to define the format of the time component of the result string.
"g" (常规日期/短时间; 标准格式字符串)"g" (general date / short time; standard format string) ShortDatePattern,用于定义结果字符串中日期部分的格式。ShortDatePattern, to define the format of the date component of the result string.

ShortTimePattern,用于定义结果字符串的时间部分的格式。ShortTimePattern, to define the format of the time component of the result string.
"G" (常规日期/长时间; 标准格式字符串)"G" (general date / long time; standard format string) ShortDatePattern,用于定义结果字符串中日期部分的格式。ShortDatePattern, to define the format of the date component of the result string.

LongTimePattern,用于定义结果字符串的时间部分的格式。LongTimePattern, to define the format of the time component of the result string.
"M"、"m" (月/日; 标准格式字符串)"M", "m" (month/day; standard format string) MonthDayPattern,用于定义结果字符串的总体格式。MonthDayPattern, to define the overall format of the result string.
"O"、"o" (往返日期/时间; 标准格式字符串)"O", "o" (round-trip date/time; standard format string) 无。None.
"R"、"r" (RFC1123; 标准格式字符串)"R", "r" (RFC1123; standard format string) RFC1123Pattern,用于定义符合 RFC 1123 标准的结果字符串。RFC1123Pattern, to define a result string that conforms to the RFC 1123 standard. 该属性是只读的。The property is read-only.
"s" (可排序的日期/时间; 标准格式字符串)"s" (sortable date/time; standard format string) SortableDateTimePattern,用于定义符合 ISO 8601 标准的结果字符串。SortableDateTimePattern, to define a result string that conforms to the ISO 8601 standard. 该属性是只读的。The property is read-only.
"t" (短时间; 标准格式字符串)"t" (short time; standard format string) ShortTimePattern,用于定义结果字符串的总体格式。ShortTimePattern, to define the overall format of the result string.
"T" (长时间; 标准格式字符串)"T" (long time; standard format string) LongTimePattern,用于定义结果字符串的总体格式。LongTimePattern, to define the overall format of the result string.
"u" (通用可排序日期/时间; 标准格式字符串)"u" (universal sortable date/time; standard format string) UniversalSortableDateTimePattern,用于定义符合协调世界时 ISO 8601 标准的结果字符串。UniversalSortableDateTimePattern, to define a result string that conforms to the ISO 8601 standard for coordinated universal time. 该属性是只读的。The property is read-only.
"U" (通用完整日期/时间; 标准格式字符串)"U" (universal full date/time; standard format string) FullDateTimePattern,用于定义结果字符串的总体格式。FullDateTimePattern, to define the overall format of the result string.
"Y"、"y" (年月; 标准格式字符串)"Y", "y" (year month; standard format string) YearMonthPattern,用于定义结果字符串的总体格式。YearMonthPattern, to define the overall format of the result string.
"ddd" (自定义格式说明符)"ddd" (custom format specifier) AbbreviatedDayNames,在结果字符串中包含一周中某天的缩写名称。AbbreviatedDayNames, to include the abbreviated name of the day of the week in the result string.
"g"、"gg" (自定义格式说明符)"g", "gg" (custom format specifier) GetEraName调用方法以将纪元名称插入到结果字符串中。Calls the GetEraName method to insert the era name in the result string.
"MMM" (自定义格式说明符)"MMM" (custom format specifier) AbbreviatedMonthNames,用于在结果字符串中包括缩写的月份名称。AbbreviatedMonthNames, to include the abbreviated month name in the result string.
"MMMM" (自定义格式说明符)"MMMM" (custom format specifier) MonthNamesMonthGenitiveNames为,则在结果字符串中包含完整的月份名称。MonthNames or MonthGenitiveNames, to include the full month name in the result string.
"t" (自定义格式说明符)"t" (custom format specifier) AMDesignator如果PMDesignator为,则在结果字符串中包括 AM/PM 指示符的第一个字符。AMDesignator or PMDesignator, to include the first character of the AM/PM designator in the result string.
"tt" (自定义格式说明符)"tt" (custom format specifier) AMDesignator如果PMDesignator为,则在结果字符串中包含完整的 AM/PM 指示符。AMDesignator or PMDesignator, to include the full AM/PM designator in the result string.
":" (自定义格式说明符)":" (custom format specifier) TimeSeparator,用于在结果字符串中包含时间分隔符。TimeSeparator, to include the time separator in the result string.
"/" (自定义格式说明符)"/" (custom format specifier) DateSeparator,将日期分隔符包含在结果字符串中。DateSeparator, to include the date separator in the result string.

修改 DateTimeFormatInfo 属性Modifying DateTimeFormatInfo properties

可以通过修改可写DateTimeFormatInfo对象的关联属性来更改日期和时间格式字符串生成的结果字符串。You can change the result string produced by date and time format strings by modifying the associated properties of a writable DateTimeFormatInfo object. 若要确定DateTimeFormatInfo对象是否可写,请IsReadOnly使用属性。To determine if a DateTimeFormatInfo object is writable, use the IsReadOnly property. 以这种DateTimeFormatInfo方式自定义对象:To customize a DateTimeFormatInfo object in this way:

  1. 创建要修改其格式设置约定的DateTimeFormatInfo对象的读/写副本。Create a read/write copy of a DateTimeFormatInfo object whose formatting conventions you want to modify. (请参阅实例化 DateTimeFormatInfo 对象部分。)(See the Instantiating a DateTimeFormatInfo object section.)

  2. 修改用于生成所需结果字符串的属性。Modify the property or properties that are used to produce the desired result string. (有关格式化方法如何使用DateTimeFormatInfo属性来定义结果字符串的信息,请参阅上一节 "格式字符串和 DateTimeFormatInfo 属性"。)(For information about how formatting methods use DateTimeFormatInfo properties to define result strings, see the previous section, Format strings and DateTimeFormatInfo properties.)

  3. 在对格式DateTimeFormatInfo设置方法的调用中IFormatProvider使用创建的自定义对象作为参数。Use the custom DateTimeFormatInfo object you created as the IFormatProvider argument in calls to formatting methods.

还可以通过两种方法更改结果字符串的格式:There are two other ways to change the format of a result string:

  • 您可以使用CultureAndRegionInfoBuilder类定义自定义区域性(具有唯一名称和对现有区域性进行补充的区域性)或替换区域性(使用而不是特定区域性)。You can use the CultureAndRegionInfoBuilder class to define either a custom culture (a culture that has a unique name and that supplements existing cultures) or a replacement culture (one that is used instead of a specific culture). 您可以通过编程方式来保存和访问此区域性, CultureInfo就像 .NET Framework 支持的任何对象一样。You can save and access this culture programmatically as you would any CultureInfo object supported by the .NET Framework.

  • 如果结果字符串不区分区域性并且不遵循预定义格式,则可以使用自定义日期和时间格式字符串。If the result string is not culture-sensitive and doesn't follow a predefined format, you can use a custom date and time format string. 例如,如果要以格式 YYYYMMDDHHmmss 序列化日期和时间数据,则可以通过将自定义格式字符串传递给DateTime.ToString(String)方法来生成结果字符串,也可以DateTime通过调用DateTime.ParseExact方法。For example, if you are serializing date and time data in the format YYYYMMDDHHmmss, you can generate the result string by passing the custom format string to the DateTime.ToString(String) method, and you can convert the result string back to a DateTime value by calling the DateTime.ParseExact method.

更改短日期模式Changing the short date pattern

下面的示例更改 "d" (短日期)标准格式字符串生成的结果字符串的格式。The following example changes the format of a result string produced by the "d" (short date) standard format string. 它将 en-us 或ShortDatePattern英语(美国)区域性的关联属性从其默认值 "M/d/yyyy" 更改为 "yyyy"-"MM"-"dd",并使用 "d" 标准格式字符串来显示ShortDatePattern属性之前和之后的日期经过.It changes the associated ShortDatePattern property for the en-US or English (United States) culture from its default of "M/d/yyyy" to "yyyy'-"MM"-"dd" and uses the "d" standard format string to display the date both before and after the ShortDatePattern property is changed.

using System;
using System.Globalization;

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

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

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

更改日期分隔符字符Changing the date separator character

下面的示例更改DateTimeFormatInfo对象中的日期分隔符字符,该对象表示 fr-fr 区域性的格式设置约定。The following example changes the date separator character in a DateTimeFormatInfo object that represents the formatting conventions of the fr-FR culture. 该示例使用 "g" 标准格式字符串在DateSeparator属性更改前后显示日期。The example uses the "g" standard format string to display the date both before and after the DateSeparator property is changed.

using System;
using System.Globalization;

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

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

更改日期名称缩写和长日期模式Changing day name abbreviations and the long date pattern

在某些情况下,长日期模式通常会显示完整的日期和月份名称以及月份和年份中的日期,可能太长。In some cases, the long date pattern, which typically displays the full day and month name along with the number of the day of the month and the year, may be too long. 下面的示例为 en-us 区域性缩短了长日期模式,以返回一个字符或两个字符的日期缩写,后跟日号、月份名称缩写和年份。The following example shortens the long date pattern for the en-US culture to return a one-character or two-character day name abbreviation followed by the day number, the month name abbreviation, and the year. 它通过为AbbreviatedDayNames数组分配较短的日期名称缩写,并修改分配给该LongDatePattern属性的自定义格式字符串来实现此功能。It does this by assigning shorter day name abbreviations to the AbbreviatedDayNames array, and by modifying the custom format string assigned to the LongDatePattern property. 这会影响 "D" 和 "f" 标准格式字符串返回的结果字符串。This affects the result strings returned by the "D" and "f" standard format strings.

using System;
using System.Globalization;

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

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

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

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

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

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

通常,对LongDatePattern属性所做的更改也FullDateTimePattern会影响属性,后者又定义了 "F" 标准格式字符串返回的结果字符串。Ordinarily, the change to the LongDatePattern property also affects the FullDateTimePattern property, which in turn defines the result string returned by the "F" standard format string. 若要保留最初的完整日期和时间模式,此示例将在修改FullDateTimePattern LongDatePattern属性后重新分配分配给该属性的原始自定义格式字符串。To preserve the original full date and time pattern, the example reassigns the original custom format string assigned to the FullDateTimePattern property after the LongDatePattern property is modified.

从12小时制更改为24小时制Changing from a 12-hour clock to a 24-hour clock

对于 .NET Framework 中的许多区域性,使用12小时制和 AM/PM 指示符来表示时间。For many cultures in the .NET Framework, the time is expressed by using a 12-hour clock and an AM/PM designator. 下面的示例定义了ReplaceWith24HourClock一个方法,该方法将使用12小时制的任何时间格式替换为使用24小时制的格式。The following example defines a ReplaceWith24HourClock method that replaces any time format that uses a 12-hour clock with a format that uses a 24-hour clock.

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

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

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

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

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

该示例使用正则表达式修改格式字符串。The example uses a regular expression to modify the format string. 正则表达式模式@"^(?<openAMPM>\s*t+\s*)? (?(openAMPM) h+(?<nonHours>[^ht]+)$ | \s*h+(?<nonHours>[^ht]+)\s*t+)的定义如下:The regular expression pattern @"^(?<openAMPM>\s*t+\s*)? (?(openAMPM) h+(?<nonHours>[^ht]+)$ | \s*h+(?<nonHours>[^ht]+)\s*t+) is defined as follows:

模式Pattern 说明Description
^ 从字符串开头开始匹配。Begin the match at the beginning of the string.
(?<openAMPM>\s*t+\s*)? 匹配零个或多个空白字符的零个或一个匹配项,后跟字母 "t" (一次或多次),后跟零个或多个空白字符。Match zero or one occurrence of zero or more white-space characters, followed by the letter "t" one or more times, followed by zero or more white-space characters. 此捕获组的名称openAMPM为。This capturing group is named openAMPM.
(?(openAMPM) h+(?<nonHours>[^ht]+)$ openAMPM如果组有匹配项,则匹配字母 "h" 一次或多次,后跟一个或多个不是 "h" 和 "t" 的字符。If the openAMPM group has a match, match the letter "h" one or more times, followed by one or more characters that are neither "h" nor "t". 匹配结束于字符串的末尾。The match ends at the end of the string. 在名为nonHours的捕获组中包含 "h" 后捕获的所有字符。All characters captured after "h" are included in a capturing group named nonHours.
&#124; \s*h+(?<nonHours>[^ht]+)\s*t+) openAMPM如果组没有匹配项,则匹配字母 "h" 一次或多次,后跟一个或多个不是 "h" 和 "t" 的字符,再后跟零个或多个空白字符。If the openAMPM group does not have a match, match the letter "h" one or more times, followed by one or more characters that are neither "h" nor "t", followed by zero or more white-space characters. 最后,匹配字母 "t" 的一个或多个匹配项。Finally, match one or more occurrences of the letter "t". 在名为nonHours的捕获组中包含 "h" 之后和空格和 "t" 之前捕获的所有字符。All characters captured after "h" and before the white-spaces and "t" are included in a capturing group named nonHours.

nonHours捕获组包含自定义日期和时间格式字符串的分钟数,还可能包含自定义日期和时间格式字符串的第二个组成部分以及任何时间分隔符符号。The nonHours capturing group contains the minute and possibly the second component of a custom date and time format string, along with any time separator symbols. 替换模式HH${nonHours}在这些元素前面预置子字符串 "HH"。The replacement pattern HH${nonHours} prepends the substring "HH" to these elements.

显示和更改日期中的纪元Displaying and changing the era in a date

下面的示例将 "g" 自定义格式说明符添加到LongDatePattern对象的属性中,该对象表示 en-us 区域性的格式设置约定。The following example adds the "g" custom format specifier to the LongDatePattern property of an object that represents the formatting conventions of the en-US culture. 此加法会影响以下三个标准格式字符串:This addition affects the following three standard format strings:

  • "D" (长日期)标准格式字符串,直接映射到LongDatePattern属性。The "D" (long date) standard format string, which maps directly to the LongDatePattern property.

  • "F" (完整日期/短时间)标准格式字符串,该字符串产生的结果字符串连接LongDatePatternShortTimePattern属性生成的子字符串。The "f" (full date / short time) standard format string, which produces a result string that concatenates the substrings produced by the LongDatePattern and ShortTimePattern properties.

  • "F" (完整日期/长时间)标准格式字符串,它直接映射到FullDateTimePattern属性。The "F" (full date / long time) standard format string, which maps directly to the FullDateTimePattern property. 由于我们未显式设置此属性值,因此它通过LongDatePattern连接和LongTimePattern属性动态生成。Because we have not explicitly set this property value, it is generated dynamically by concatenating the LongDatePattern and LongTimePattern properties.

该示例还演示了如何更改其日历具有单个纪元的区域性的纪元名称。The example also shows how to change the era name for a culture whose calendar has a single era. 在这种情况下,en-us 区域性使用公历,该日历由GregorianCalendar对象表示。In this case, the en-US culture uses the Gregorian calendar, which is represented by a GregorianCalendar object. GregorianCalendar类支持单个纪元,其名称为公元The GregorianCalendar class supports a single era, which it names A.D. (基督公元)。(Anno Domini). 该示例将纪元名称更改为公元The example changes the era name to C.E. (Common 年代),方法是将 "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. 和方法转换可以具有各种格式的字符串,而ParseExactTryParseExact要求字符串具有定义的格式或格式。 TryParse ParseThe Parse and TryParse methods convert a string that can have a variety of formats, whereas ParseExact and TryParseExact require that the string have a defined format or formats. 如果分析操作Parse失败, ParseExact则会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如果DateTimeStyles.AllowTrailingWhite DateTimeStyles.AllowLeadingWhite DateTimeStyles.AllowWhiteSpaces DateTimeStyles.AllowInnerWhite调用或方法TryParse时没有提供值,则默认值为,它是包含、和标志的复合样式。 ParseIf you don't provide a DateTimeStyles value when you call the Parse or TryParse method, the default is DateTimeStyles.AllowWhiteSpaces, which is a composite style that includes the DateTimeStyles.AllowLeadingWhite, DateTimeStyles.AllowTrailingWhite, and DateTimeStyles.AllowInnerWhite flags. ParseExact对于和TryParseExact 方法,默认值为;输入字符串必须精确对应于特定的自定义日期和DateTimeStyles.None时间格式字符串。For the ParseExact and TryParseExact methods, the default is DateTimeStyles.None; the input string must correspond precisely to a particular custom date and time format string.

解析方法还可以隐式或显式地DateTimeFormatInfo使用一个对象,该对象定义可在要分析的字符串中出现的特定符号和模式。The parsing methods also implicitly or explicitly use a DateTimeFormatInfo object that defines the specific symbols and patterns that can occur in the string to be parsed. 如果未提供DateTimeFormatInfo对象DateTimeFormatInfo ,则默认情况下将使用当前线程区域性的对象。If you don't provide a DateTimeFormatInfo object, the DateTimeFormatInfo object for the current thread culture is used by default. 有关分析日期和时间字符串的详细信息,请参阅各种分析方法DateTime.Parse,例如DateTimeOffset.ParseExactDateTime.TryParse、和DateTimeOffset.TryParseExactFor more information about parsing date and time strings, see the individual parsing methods, such as DateTime.Parse, DateTime.TryParse, DateTimeOffset.ParseExact, and DateTimeOffset.TryParseExact.

下面的示例演示分析日期和时间字符串的区分区域性的特性。The following example illustrates the culture-sensitive nature of parsing date and time strings. 它尝试使用 en-us、en-GB、fr-fr 和 wi-fi 区域性约定来分析两个日期字符串。It tries to parse two date strings by using the conventions of the en-US, en-GB, fr-FR, and fi-FI cultures. 在 en-us 区域性中解释为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 and dynamic data部分。For information about how to instantiate a DateTimeFormatInfo object that reflects user cultural customizations, see the DateTimeFormatInfo and dynamic data section.

下面的示例说明了反映用户区域性设置的分析操作与不是的操作之间的差异。The following example illustrates the difference between a parsing operation that reflects user cultural settings and one that does not. 在这种情况下,默认系统区域性为 en-us,但用户已使用 "控制面板"、"区域和语言" 将短日期模式从其默认值 "M/d/yyyy" 更改为 "YY/MM/dd"。In this case, the default system culture is en-US, but the user has used Control Panel, Region and Language to change the short date pattern from its default of "M/d/yyyy" to "yy/MM/dd". 如果用户输入的字符串反映用户设置,并且该字符串由DateTimeFormatInfo还反映用户设置(重写)的对象进行分析,则分析操作将返回正确的结果。When the user enters a string that reflects user settings, and the string is parsed by a DateTimeFormatInfo object that also reflects user settings (overrides), the parsing operation returns a correct result. 但是,当通过DateTimeFormatInfo反映标准 en-us 区域性设置的对象对字符串进行分析时,分析方法会FormatException引发异常,因为它会将14解释为月份号,而不是年份的最后两位数字。However, when the string is parsed by a DateTimeFormatInfo object that reflects standard en-US cultural settings, the parsing method throws a FormatException exception because it interprets 14 as the number of the month, not the last two digits of the year.

using System;
using System.Globalization;

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

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

序列化和反序列化日期和时间数据Serializing and deserializing date and time data

序列化日期和时间数据应为往返行程;也就是说,所有序列化和反序列化的值都应相同。Serialized date and time data are expected to round-trip; that is, all serialized and deserialized values should be identical. 如果日期和时间值表示一个时刻,则反序列化的值应同时表示同一时间点,而不考虑在其上还原它的系统的区域性或时区。If a date and time value represents a single moment in time, the deserialized value should represent the same moment in time regardless of the culture or time zone of the system on which it was restored. 若要成功往返日期和时间数据,必须使用InvariantInfo属性返回的固定区域性的约定来生成和分析数据。To round-trip date and time data successfully, you must use the conventions of the invariant culture, which is returned by the InvariantInfo property, to generate and parse the data. 格式设置和分析操作决不会反映默认区域性的约定。The formatting and parsing operations should never reflect the conventions of the default culture. 如果使用默认区域性设置,数据的可移植性将受到严格限制;它只能在其特定于区域性的设置与对其进行序列化的线程相同的线程上成功进行反序列化。If you use default cultural settings, the portability of the data is strictly limited; it can be successfully deserialized only on a thread whose cultural-specific settings are identical to those of the thread on which it was serialized. 在某些情况下,这意味着甚至无法在同一系统上成功序列化和反序列化数据。In some cases, this means that the data cannot even be successfully serialized and deserialized on the same system.

如果日期和时间值的时间部分很重要,还应将其转换为 UTC,并使用 "o" 或 "r"标准格式字符串序列化。If the time component of a date and time value is significant, it should also be converted to UTC and serialized by using the "o" or "r" standard format string. 然后,可以通过调用分析方法并向其传递适当的格式字符串和固定区域性作为provider参数来还原时间数据。The time data can then be restored by calling a parsing method and passing it the appropriate format string along with the invariant culture as the provider argument.

下面的示例演示了往返日期和时间值的过程。The following example illustrates the process of round-tripping a date and time value. 它序列化系统中的日期和时间,该系统遵循美国太平洋时间,当前区域性为 en-us。It serializes a date and time on a system that observes U.S. Pacific time and whose current culture is en-US.

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

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

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

它反序列化在布鲁塞尔、哥本哈根、马德里和巴黎时区中的系统上的数据,其当前区域性为 fr-fr。It deserializes the data on a system in the Brussels, Copenhagen, Madrid and Paris time zone and whose current culture is fr-FR. 还原日期比原始日期晚9个小时,这反映了时区在 UTC 后8小时的时间调整为早于 UTC 的一小时。The restored date is nine hours later than the original date, which reflects the time zone adjustment from eight hours behind UTC to one hour ahead of UTC. 原始日期和还原日期均表示同一时刻。Both the original date and the restored date represent the same moment in time.

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

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

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

构造函数

DateTimeFormatInfo()

初始化不依赖于区域性的(固定的)DateTimeFormatInfo 类的新可写实例。Initializes a new writable instance of the DateTimeFormatInfo class that is culture-independent (invariant).

属性

AbbreviatedDayNames

获取或设置 String 类型的一维数组,它包含周中各天的区域性特定的缩写名称。Gets or sets a one-dimensional array of type String containing the culture-specific abbreviated names of the days of the week.

AbbreviatedMonthGenitiveNames

获取或设置与当前 DateTimeFormatInfo 对象关联的月份缩写名称的字符串数组。Gets or sets a string array of abbreviated month names associated with the current DateTimeFormatInfo object.

AbbreviatedMonthNames

获取或设置一维字符串数组,它包含各月的特定于区域性的缩写名称。Gets or sets a one-dimensional string array that contains the culture-specific abbreviated names of the months.

AMDesignator

获取或设置表示处于"上午"(中午前)的各小时的字符串指示项。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

获取或设置一个值,该值指定使用哪一规则确定该年的第一个日历周。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

获取与当前 DateTimeFormatInfo 对象关联的本机日历名称。Gets the native name of the calendar associated with the current DateTimeFormatInfo object.

PMDesignator

获取或设置表示处于"下午"(中午后)的各小时的字符串指示项。Gets or sets the string designator for hours that are "post meridiem" (after noon).

RFC1123Pattern

获取自定义的格式字符串,该字符串用于基于 Internet 工程任务组 (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)

返回与指定 IFormatProvider 关联的 DateTimeFormatInfo 对象。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)

适用于

另请参阅