DateTimeFormatInfo DateTimeFormatInfo DateTimeFormatInfo DateTimeFormatInfo Class

定义

提供有关日期和时间值格式的区域性特定信息。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
继承
DateTimeFormatInfoDateTimeFormatInfoDateTimeFormatInfoDateTimeFormatInfo
属性
实现

示例

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

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

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

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

注解

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

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

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

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

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

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

  • 日历日期表示。The calendar in which dates are expressed.

本节内容:In this section:

实例化 DateTimeFormatInfo 对象Instantiating a DateTimeFormatInfo object

一个DateTimeFormatInfo对象可以表示固定区域性、 特定区域性、 一个非特定区域性或当前区域性的格式设置约定。A DateTimeFormatInfo object can represent the formatting conventions of the invariant culture, a specific culture, a neutral culture, or the current culture. 本部分讨论了如何实例化每种类型的DateTimeFormatInfo对象。This section discusses how to instantiate each type of DateTimeFormatInfo object.

实例化用于固定区域性的 DateTimeFormatInfo 对象Instantiating a DateTimeFormatInfo object for the invariant culture

固定的区域性表示是不区分区域性的区域性。The invariant culture represents a culture that is culture-insensitive. 它基于英语的语言,但不是在任何特定说英语的国家/地区。It is based on the English language, but not on any specific English-speaking country/region. 尽管特定区域性的数据可以是动态和可以更改以反映新的区域性约定或用户首选项,固定区域性的数据不会更改。Although the data of specific cultures can be dynamic and can change to reflect new cultural conventions or user preferences, the data of the invariant culture does not change. 可以实例化DateTimeFormatInfo对象,表示固定区域性的格式设置约定按以下方式:You can instantiate a DateTimeFormatInfo object that represents the formatting conventions of the invariant culture in the following ways:

下面的示例使用两种方法来实例化DateTimeFormatInfo表示固定区域性的对象。The following example uses each of these methods to instantiate a DateTimeFormatInfo object that represents the invariant culture. 然后,它指示该对象是只读的。It then indicates whether the object is read-only.

System.Globalization.DateTimeFormatInfo dtfi; 

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

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

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

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

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

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

实例化特定区域性的 DateTimeFormatInfo 对象Instantiating a DateTimeFormatInfo object for a specific culture

特定区域性表示特定国家/地区中讲述的语言。A specific culture represents a language that is spoken in a particular country/region. 例如,EN-US 表示美国,所使用的英语语言的特定区域性,en 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. 而不是填充DateTimeFormatInfo.NET Framework 返回泛型值对象DateTimeFormatInfo反映了特定的格式设置约定的区域性的对象是非特定区域性的子级。Instead of populating the DateTimeFormatInfo object with generic values, the .NET Framework returns a DateTimeFormatInfo object that reflects the formatting conventions of a specific culture that is a child of the neutral culture. 例如,DateTimeFormatInfo对象的非特定 en 区域性反映 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
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. 例如,其区域性为英语 (美国) 的用户可能选择而不是默认 12 小时时钟 (在格式 h:mm: ss tt) 显示长时间 (采用格式: 分: 秒) 使用 24 小时制的时间值。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)构造函数,并提供的值falseuseUserOverride参数。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:。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. 在此情况下,DateTimeFormatInfo返回对象CurrentInfo属性更改为与当前区域性关联的对象。When this happens, the DateTimeFormatInfo object returned by the CurrentInfo property changes to an object associated with the current culture. 同样,区域性的日历可以更改,这可能会导致在更改为大量DateTimeFormatInfo属性值。Similarly, a culture's calendar can change, which can result in changes to numerous DateTimeFormatInfo property values.

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

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

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

CultureInfo 和 DateTimeFormatInfo 对象数据源Source of CultureInfo and DateTimeFormatInfo object 反映用户替代Reflects user overrides
CultureInfo.CurrentCulture.DateTimeFormat 属性CultureInfo.CurrentCulture.DateTimeFormat property Yes
DateTimeFormatInfo.CurrentInfo 属性DateTimeFormatInfo.CurrentInfo property Yes
CultureInfo.CreateSpecificCulture 方法CultureInfo.CreateSpecificCulture method Yes
CultureInfo.GetCultureInfo 方法CultureInfo.GetCultureInfo method NoNo
CultureInfo.CultureInfo(String) 构造函数CultureInfo.CultureInfo(String) constructor Yes
CultureInfo.CultureInfo(String, Boolean) 构造函数CultureInfo.CultureInfo(String, Boolean) constructor 取决于值useUserOverride参数Depends 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接口包含一个方法, IFormatProvider.GetFormat(Type)The IFormatProvider interface includes a single method, IFormatProvider.GetFormat(Type). 此回调方法传递Type表示提供格式设置信息所需的类型的对象。This callback method is passed a Type object that represents the type needed to provide formatting information. 该方法返回该类型的实例或null如果它不能提供的类型的实例。The method returns either an instance of that type or null if it cannot provide an instance of the type. .NET Framework 包括两个IFormatProvider格式化日期和时间的实现:The .NET Framework includes two IFormatProvider implementations for formatting dates and times:

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

下面的示例说明之间的关系IFormatProvider接口和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[])方法请求NumberFormatInfoDateTimeFormatInfo对象以及ICustomFormatter实现。As the output from the example shows, the Decimal.ToString(IFormatProvider) method requests a DateTimeFormatInfo object to provide formatting information, whereas the String.Format(IFormatProvider, String, Object[]) method requests NumberFormatInfo and DateTimeFormatInfo objects as well as an ICustomFormatter implementation.

using System;
using System.Globalization;

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

public class Example
{
   public static void Main()
   {
      DateTime dateValue = new DateTime(2013, 5, 28, 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) AMDesignatorPMDesignator,以在结果字符串中包括 AM/PM 指示符的第一个字符。AMDesignator or PMDesignator, to include the first character of the AM/PM designator in the result string.
"tt"(自定义格式说明符)"tt" (custom format specifier) AMDesignatorPMDesignator,结果字符串中包含完整 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. 更改关联ShortDatePatternEN-US 或英语 (美国) 区域性从其默认值为"年-月-日"到属性"yyyy-"MM"-"dd",并使用"d"标准格式字符串来显示日期之前和之后ShortDatePattern属性更改。It changes the associated ShortDatePattern property for the en-US or English (United States) culture from its default of "M/d/yyyy" to "yyyy'-"MM"-"dd" and uses the "d" standard format string to display the date both before and after the ShortDatePattern property is changed.

using System;
using System.Globalization;

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

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

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

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

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

using System;
using System.Globalization;

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

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

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

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

using System;
using System.Globalization;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

该示例还演示如何更改的区域性的日历具有单个纪元纪元名称。The example also shows how to change the era name for a culture whose calendar has a single era. 在这种情况下,EN-US 区域性使用公历,由表示GregorianCalendar对象。In this case, the en-US culture uses the Gregorian calendar, which is represented by a GregorianCalendar object. GregorianCalendar类支持单个纪元,其名称公元The GregorianCalendar class supports a single era, which it names A.D. (午夜 11:59:59 止)。(Anno Domini). 该示例的纪元名称更改为公元The example changes the era name to C.E. (基督纪元) 替换为分配给在格式字符串中的"g"自定义格式说明符FullDateTimePattern文本字符串的属性。(Common Era) by replacing the "g" custom format specifier in the format string assigned to the FullDateTimePattern property with a literal string. 文字字符串的使用是有必要,因为纪元名称通常由返回GetEraName方法从.NET Framework 或 Windows 操作系统提供的区域性表中的专用数据。The use of a literal string is necessary, because the era name is typically returned by the GetEraName method from private data in the culture tables supplied by either the .NET Framework or the Windows operating system.

using System;
using System.Globalization;

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

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

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

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

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

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

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

分析日期和时间字符串Parsing date and time strings

分析涉及转换的日期和时间的字符串表示形式DateTimeDateTimeOffset值。Parsing involves converting the string representation of a date and time to a DateTime or DateTimeOffset value. 这两种类型包括ParseTryParseParseExact,和TryParseExact方法,以支持分析操作。Both of these types include the Parse, TryParse, ParseExact, and TryParseExact methods to support parsing operations. ParseTryParse方法将转换可以具有多种格式的字符串,而ParseExactTryParseExact要求字符串具有定义的格式。The Parse and TryParse methods convert a string that can have a variety of formats, whereas ParseExact and TryParseExact require that the string have a defined format or formats. 如果在分析操作失败,ParseParseExact引发异常,而TryParseTryParseExact返回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值在调用时ParseTryParse方法中,默认值是DateTimeStyles.AllowWhiteSpaces,这是包含的复合样式DateTimeStyles.AllowLeadingWhiteDateTimeStyles.AllowTrailingWhite,和DateTimeStyles.AllowInnerWhite标志。If you don't provide a DateTimeStyles value when you call the Parse or TryParse method, the default is DateTimeStyles.AllowWhiteSpaces, which is a composite style that includes the DateTimeStyles.AllowLeadingWhite, DateTimeStyles.AllowTrailingWhite, and DateTimeStyles.AllowInnerWhite flags. 有关ParseExactTryParseExact方法,默认值是DateTimeStyles.None; 输入的字符串必须精确对应特定自定义日期和时间格式字符串。For the ParseExact and TryParseExact methods, the default is DateTimeStyles.None; the input string must correspond precisely to a particular custom date and time format string.

分析方法还将隐式或显式使用DateTimeFormatInfo对象,用于定义特定符号和模式,可在要分析的字符串中出现。The parsing methods also implicitly or explicitly use a DateTimeFormatInfo object that defines the specific symbols and patterns that can occur in the string to be parsed. 如果未提供DateTimeFormatInfo对象,DateTimeFormatInfo对象默认情况下使用当前线程区域性。If you don't provide a DateTimeFormatInfo object, the DateTimeFormatInfo object for the current thread culture is used by default. 有关分析日期和时间字符串的详细信息,请参阅单独的分析方法,如DateTime.ParseDateTime.TryParseDateTimeOffset.ParseExact,和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 和 FI-FI 区域性的约定来分析两个日期字符串。It tries to parse two date strings by using the conventions of the en-US, en-GB, fr-FR, and fi-FI cultures. 将被解释为 8/18/2014 在 EN-US 中的日期的区域性,则会引发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. 2015 年 1 月 2 日被解析为 EN-US 区域性中的第一个月的第二天,但剩余区域性中的第二个月的第一天。1/2/2015 is parsed as the second day of the first month in the en-US culture, but as the first day of the second month in the remaining cultures.

using System;
using System.Globalization;

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

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

通常有两个原因分析日期和时间的字符串:Date and time strings are typically parsed for two reasons:

  • 若要将用户输入转换为日期和时间值。To convert user input into a date and time value.

  • 往返日期和时间值;也就是说,要反序列化之前序列化为字符串的日期和时间值。To round-trip a date and time value; that is, to deserialize a date and time value that was previously serialized as a string.

以下各节讨论中更详细地介绍这两个操作。The following sections discuss these two operations in greater detail.

分析用户字符串Parsing user strings

当分析用户输入的日期和时间字符串时,始终应实例化DateTimeFormatInfo反映用户的区域性设置,包括用户可能已做的任何自定义的对象。When you parse date and time strings input by the user, you should always instantiate a DateTimeFormatInfo object that reflects the user's cultural settings, including any customizations the user may have made. 否则,日期和时间对象可能不正确的值。Otherwise, the date and time object may have incorrect values. 有关如何实例化DateTimeFormatInfo对象,用于反映用户区域性的自定义设置,请参阅DateTimeFormatInfo 和动态数据部分。For information about how to instantiate a DateTimeFormatInfo object that reflects user cultural customizations, see the DateTimeFormatInfo and dynamic data section.

下面的示例演示的分析操作中反映了用户的区域性设置和一个不之间的差异。The following example illustrates the difference between a parsing operation that reflects user cultural settings and one that does not. 在这种情况下,默认系统区域性为 EN-US,但用户使用控制面板中,区域和语言从其默认值为"年-月-日"的短日期模式更改为"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. 还原后的日期是九个小时后于原始日期,这反映了比 utc 晚八个小时内为早于 utc 时间一小时的时区调整。The restored date is nine hours later than the original date, which reflects the time zone adjustment from eight hours behind UTC to one hour ahead of UTC. 原始日期和还原后的日期表示同一时刻。Both the original date and the restored date represent the same moment in time.

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

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

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

构造函数

DateTimeFormatInfo() DateTimeFormatInfo() DateTimeFormatInfo() DateTimeFormatInfo()

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

属性

AbbreviatedDayNames AbbreviatedDayNames AbbreviatedDayNames 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 AbbreviatedMonthGenitiveNames AbbreviatedMonthGenitiveNames AbbreviatedMonthGenitiveNames

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

AbbreviatedMonthNames AbbreviatedMonthNames AbbreviatedMonthNames AbbreviatedMonthNames

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

AMDesignator AMDesignator AMDesignator AMDesignator

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

Calendar Calendar Calendar Calendar

获取或设置用于当前区域性的日历。Gets or sets the calendar to use for the current culture.

CalendarWeekRule CalendarWeekRule CalendarWeekRule CalendarWeekRule

获取或设置一个值,该值指定使用哪一规则确定该年的第一个日历周。Gets or sets a value that specifies which rule is used to determine the first calendar week of the year.

CurrentInfo CurrentInfo CurrentInfo CurrentInfo

获取基于当前区域性对值进行格式设置的只读的 DateTimeFormatInfo 对象。Gets a read-only DateTimeFormatInfo object that formats values based on the current culture.

DateSeparator DateSeparator DateSeparator DateSeparator

获取或设置分隔日期中各组成部分(即年、月、日)的字符串。Gets or sets the string that separates the components of a date, that is, the year, month, and day.

DayNames DayNames DayNames DayNames

获取或设置包含该周中各天的特定于区域性的完整名称的一维字符串数组。Gets or sets a one-dimensional string array that contains the culture-specific full names of the days of the week.

FirstDayOfWeek FirstDayOfWeek FirstDayOfWeek FirstDayOfWeek

获取或设置该周的第一天。Gets or sets the first day of the week.

FullDateTimePattern FullDateTimePattern FullDateTimePattern FullDateTimePattern

为长日期和长时间值获取或设置自定义格式字符串。Gets or sets the custom format string for a long date and long time value.

InvariantInfo InvariantInfo InvariantInfo InvariantInfo

获取不依赖于区域性的(固定)默认只读的 DateTimeFormatInfo 对象。Gets the default read-only DateTimeFormatInfo object that is culture-independent (invariant).

IsReadOnly IsReadOnly IsReadOnly IsReadOnly

获取一个值,该值指示 DateTimeFormatInfo 对象是否为只读。Gets a value indicating whether the DateTimeFormatInfo object is read-only.

LongDatePattern LongDatePattern LongDatePattern LongDatePattern

获取或设置长日期值的自定义格式字符串。Gets or sets the custom format string for a long date value.

LongTimePattern LongTimePattern LongTimePattern LongTimePattern

为长时间值获取或设置自定义格式字符串。Gets or sets the custom format string for a long time value.

MonthDayPattern MonthDayPattern MonthDayPattern MonthDayPattern

为月和日值获取或设置自定义格式字符串。Gets or sets the custom format string for a month and day value.

MonthGenitiveNames MonthGenitiveNames MonthGenitiveNames MonthGenitiveNames

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

MonthNames MonthNames MonthNames MonthNames

获取或设置 String 类型的一维数组,它包含月份的区域性特定的全名。Gets or sets a one-dimensional array of type String containing the culture-specific full names of the months.

NativeCalendarName NativeCalendarName NativeCalendarName NativeCalendarName

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

PMDesignator PMDesignator PMDesignator PMDesignator

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

RFC1123Pattern RFC1123Pattern RFC1123Pattern 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 ShortDatePattern ShortDatePattern ShortDatePattern

为短日期值获取或设置自定义格式字符串。Gets or sets the custom format string for a short date value.

ShortestDayNames ShortestDayNames ShortestDayNames ShortestDayNames

获取或设置与当前 DateTimeFormatInfo 对象关联的唯一最短日期缩写名称的字符串数组。Gets or sets a string array of the shortest unique abbreviated day names associated with the current DateTimeFormatInfo object.

ShortTimePattern ShortTimePattern ShortTimePattern ShortTimePattern

为短时间值获取或设置自定义格式字符串。Gets or sets the custom format string for a short time value.

SortableDateTimePattern SortableDateTimePattern SortableDateTimePattern SortableDateTimePattern

获取可排序数据和时间值的自定义格式字符串。Gets the custom format string for a sortable date and time value.

TimeSeparator TimeSeparator TimeSeparator TimeSeparator

获取或设置分隔时间中各组成部分(即小时、分钟和秒钟)的字符串。Gets or sets the string that separates the components of time, that is, the hour, minutes, and seconds.

UniversalSortableDateTimePattern UniversalSortableDateTimePattern UniversalSortableDateTimePattern UniversalSortableDateTimePattern

获取 ISO 8601 定义的通用的可排序日期和时间字符串的自定义格式字符串。Gets the custom format string for a universal, sortable date and time string, as defined by ISO 8601.

YearMonthPattern YearMonthPattern YearMonthPattern YearMonthPattern

为年和月值获取或设置自定义格式字符串。Gets or sets the custom format string for a year and month value.

方法

Clone() Clone() Clone() Clone()

创建 DateTimeFormatInfo 的浅表副本。Creates a shallow copy of the DateTimeFormatInfo.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetAbbreviatedDayName(DayOfWeek) GetAbbreviatedDayName(DayOfWeek) GetAbbreviatedDayName(DayOfWeek) 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) GetAbbreviatedEraName(Int32) GetAbbreviatedEraName(Int32) GetAbbreviatedEraName(Int32)

返回包含指定纪元的缩写名称的字符串(如果缩写名称存在)。Returns the string containing the abbreviated name of the specified era, if an abbreviation exists.

GetAbbreviatedMonthName(Int32) GetAbbreviatedMonthName(Int32) GetAbbreviatedMonthName(Int32) GetAbbreviatedMonthName(Int32)

基于与当前 DateTimeFormatInfo 对象关联的区域性,返回指定月份的区域性特定的缩写名称。Returns the culture-specific abbreviated name of the specified month based on the culture associated with the current DateTimeFormatInfo object.

GetAllDateTimePatterns() GetAllDateTimePatterns() GetAllDateTimePatterns() GetAllDateTimePatterns()

返回可用于对日期和时间值进行格式设置的所有标准模式。Returns all the standard patterns in which date and time values can be formatted.

GetAllDateTimePatterns(Char) GetAllDateTimePatterns(Char) GetAllDateTimePatterns(Char) GetAllDateTimePatterns(Char)

返回可使用指定标准格式字符串对日期和时间值进行格式设置的所有模式。Returns all the patterns in which date and time values can be formatted using the specified standard format string.

GetDayName(DayOfWeek) GetDayName(DayOfWeek) GetDayName(DayOfWeek) 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) GetEra(String) GetEra(String) GetEra(String)

返回表示指定纪元的整数。Returns the integer representing the specified era.

GetEraName(Int32) GetEraName(Int32) GetEraName(Int32) GetEraName(Int32)

返回包含指定纪元名称的字符串。Returns the string containing the name of the specified era.

GetFormat(Type) GetFormat(Type) GetFormat(Type) GetFormat(Type)

返回指定类型的对象,它提供日期和时间格式化服务。Returns an object of the specified type that provides a date and time formatting service.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(Inherited from Object)
GetInstance(IFormatProvider) GetInstance(IFormatProvider) GetInstance(IFormatProvider) GetInstance(IFormatProvider)

返回与指定 IFormatProvider 关联的 DateTimeFormatInfo 对象。Returns the DateTimeFormatInfo object associated with the specified IFormatProvider.

GetMonthName(Int32) GetMonthName(Int32) GetMonthName(Int32) 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) GetShortestDayName(DayOfWeek) GetShortestDayName(DayOfWeek) GetShortestDayName(DayOfWeek)

获取与当前 DateTimeFormatInfo 对象关联的周中指定日期的最短日期缩写名称。Obtains the shortest abbreviated day name for a specified day of the week associated with the current DateTimeFormatInfo object.

GetType() GetType() GetType() GetType()

获取当前实例的 TypeGets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
ReadOnly(DateTimeFormatInfo) ReadOnly(DateTimeFormatInfo) ReadOnly(DateTimeFormatInfo) ReadOnly(DateTimeFormatInfo)

返回只读的 DateTimeFormatInfo 包装。Returns a read-only DateTimeFormatInfo wrapper.

SetAllDateTimePatterns(String[], Char) SetAllDateTimePatterns(String[], Char) SetAllDateTimePatterns(String[], Char) SetAllDateTimePatterns(String[], Char)

设置对应于指定的标准格式字符串的自定义日期和时间格式字符串。Sets the custom date and time format strings that correspond to a specified standard format string.

ToString() ToString() ToString() ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(Inherited from Object)

显式界面实现

ISerializable.GetObjectData(SerializationInfo, StreamingContext) ISerializable.GetObjectData(SerializationInfo, StreamingContext) ISerializable.GetObjectData(SerializationInfo, StreamingContext) ISerializable.GetObjectData(SerializationInfo, StreamingContext)

适用于

另请参阅