标准日期和时间格式字符串Standard Date and Time Format Strings

标准日期和时间格式字符串使用单个格式说明符来定义日期和时间值的文本表示形式。A standard date and time format string uses a single format specifier to define the text representation of a date and time value. 包含一个以上字符(包括空白)的任何日期和时间格式字符串都会被解释为自定义日期和时间格式字符串;有关更多信息,请参见自定义日期和时间格式字符串Any date and time format string that contains more than one character, including white space, is interpreted as a custom date and time format string; for more information, see Custom Date and Time Format Strings. 可通过两种方式使用标准或自定义格式字符串:A standard or custom format string can be used in two ways:

  • 定义由格式设置操作生成的字符串。To define the string that results from a formatting operation.

  • 定义可通过分析操作转换为 DateTimeDateTimeOffset 值的日期和时间值的文本表示形式。To define the text representation of a date and time value that can be converted to a DateTime or DateTimeOffset value by a parsing operation.

提示

你可以下载格式设置实用工具,它属于一种 .NET Core Windows 窗体应用程序,通过该应用程序,你可将格式字符串应用于数值或日期和时间值并显示结果字符串 。You can download the Formatting Utility, a .NET Core Windows Forms application that lets you apply format strings to either numeric or date and time values and displays the result string. 源代码适用于 C#Visual BasicSource code is available for C# and Visual Basic.

标准日期和时间格式字符串可以与 DateTimeDateTimeOffset 值一起使用。Standard date and time format strings can be used with both DateTime and DateTimeOffset values.

备注

本文中的一些 C# 示例在 Try.NET 内联代码运行程序和演练环境中运行。Some of the C# examples in this article run in the Try.NET inline code runner and playground. 选择“运行”按钮以在交互窗口中运行示例 。Select the Run button to run an example in an interactive window. 执行代码后,可通过再次选择“运行”来修改它并运行已修改的代码 。Once you execute the code, you can modify it and run the modified code by selecting Run again. 已修改的代码要么在交互窗口中运行,要么编译失败时,交互窗口将显示所有 C# 编译器错误消息。The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.

Try.NET 内联代码运行程序和演练环境的本地时区是协调世界时 (UTC)。The local time zone of the Try.NET inline code runner and playground is Coordinated Universal Time, or UTC. 这可能会影响用于说明 DateTimeDateTimeOffsetTimeZoneInfo 类型及其成员的示例的行为和输出。This may affect the behavior and the output of examples that illustrate the DateTime, DateTimeOffset, and TimeZoneInfo types and their members.

下表描述了标准日期和时间格式说明符。The following table describes the standard date and time format specifiers. 除非另行说明,否则,特定的标准日期和时间格式说明符将产生相同的字符串表示形式,这与它是与 DateTime 值还是 DateTimeOffset 值一起使用无关。Unless otherwise noted, a particular standard date and time format specifier produces an identical string representation regardless of whether it is used with a DateTime or a DateTimeOffset value. 有关使用标准日期和时间格式字符串的其他信息,请参见注释部分。See the Notes section for additional information about using standard date and time format strings.

格式说明符Format specifier 说明Description 示例Examples
"d""d" 短日期模式。Short date pattern.

有关详细信息,请参阅短日期(“d”)格式说明符More information:The Short Date ("d") Format Specifier.
2009-06-15T13:45:30 -> 6/15/2009 (en-US)2009-06-15T13:45:30 -> 6/15/2009 (en-US)

2009-06-15T13:45:30 -> 15/06/2009 (fr-FR)2009-06-15T13:45:30 -> 15/06/2009 (fr-FR)

2009-06-15T13:45:30 -> 2009/06/15 (ja-JP)2009-06-15T13:45:30 -> 2009/06/15 (ja-JP)
“D”"D" 长日期模式。Long date pattern.

有关详细信息,请参阅长日期(“D”)格式说明符More information:The Long Date ("D") Format Specifier.
2009-06-15T13:45:30 -> Monday, June 15, 2009 (en-US)2009-06-15T13:45:30 -> Monday, June 15, 2009 (en-US)

2009-06-15T13:45:30 -> 15 июня 2009 г.2009-06-15T13:45:30 -> 15 июня 2009 г. (ru-RU)(ru-RU)

2009-06-15T13:45:30 -> Montag, 15.2009-06-15T13:45:30 -> Montag, 15. Juni 2009 (de-DE)Juni 2009 (de-DE)
“f”"f" 完整日期/时间模式(短时间)。Full date/time pattern (short time).

更多信息:完整日期短时间(“f”)格式说明符More information: The Full Date Short Time ("f") Format Specifier.
2009-06-15T13:45:30 -> Monday, June 15, 2009 1:45 PM (en-US)2009-06-15T13:45:30 -> Monday, June 15, 2009 1:45 PM (en-US)

2009-06-15T13:45:30 -> den 15 juni 2009 13:45 (sv-SE)2009-06-15T13:45:30 -> den 15 juni 2009 13:45 (sv-SE)

2009-06-15T13:45:30 -> Δευτέρα, 15 Ιουνίου 2009 1:45 μμ (el-GR)2009-06-15T13:45:30 -> Δευτέρα, 15 Ιουνίου 2009 1:45 μμ (el-GR)
“F”"F" 完整日期/时间模式(长时间)。Full date/time pattern (long time).

更多信息:完整日期长时间(“F”)格式说明符More information: The Full Date Long Time ("F") Format Specifier.
2009-06-15T13:45:30 -> Monday, June 15, 2009 1:45:30 PM (zh-CN)2009-06-15T13:45:30 -> Monday, June 15, 2009 1:45:30 PM (en-US)

2009-06-15T13:45:30 -> den 15 juni 2009 13:45:30 (sv-SE)2009-06-15T13:45:30 -> den 15 juni 2009 13:45:30 (sv-SE)

2009-06-15T13:45:30 -> Δευτέρα, 15 Ιουνίου 2009 1:45:30 μμ (el-GR)2009-06-15T13:45:30 -> Δευτέρα, 15 Ιουνίου 2009 1:45:30 μμ (el-GR)
“g”"g" 常规日期/时间模式(短时间)。General date/time pattern (short time).

更多信息:常规日期短时间(“g”)格式说明符More information: The General Date Short Time ("g") Format Specifier.
2009-06-15T13:45:30 -> 6/15/2009 1:45 PM (en-US)2009-06-15T13:45:30 -> 6/15/2009 1:45 PM (en-US)

2009-06-15T13:45:30 -> 15/06/2009 13:45 (es-ES)2009-06-15T13:45:30 -> 15/06/2009 13:45 (es-ES)

2009-06-15T13:45:30 -> 2009/6/15 13:45 (zh-CN)2009-06-15T13:45:30 -> 2009/6/15 13:45 (zh-CN)
“G”"G" 常规日期/时间模式(长时间)。General date/time pattern (long time).

更多信息:常规日期长时间(“G”)格式说明符More information: The General Date Long Time ("G") Format Specifier.
2009-06-15T13:45:30 -> 6/15/2009 1:45:30 PM (en-US)2009-06-15T13:45:30 -> 6/15/2009 1:45:30 PM (en-US)

2009-06-15T13:45:30 -> 15/06/2009 13:45:30 (es-ES)2009-06-15T13:45:30 -> 15/06/2009 13:45:30 (es-ES)

2009-06-15T13:45:30 -> 2009/6/15 13:45:30 (zh-CN)2009-06-15T13:45:30 -> 2009/6/15 13:45:30 (zh-CN)
“M”、“m”"M", "m" 月/日模式。Month/day pattern.

更多信息:月(“M”、“m”)格式说明符More information: The Month ("M", "m") Format Specifier.
2009-06-15T13:45:30 -> June 15 (en-US)2009-06-15T13:45:30 -> June 15 (en-US)

2009-06-15T13:45:30 -> 15.2009-06-15T13:45:30 -> 15. juni (da-DK)juni (da-DK)

2009-06-15T13:45:30 -> 15 Juni (id-ID)2009-06-15T13:45:30 -> 15 Juni (id-ID)
“O”、“o”"O", "o" 往返日期/时间模式。Round-trip date/time pattern.

更多信息:往返(“O”、“o”)格式说明符More information: The Round-trip ("O", "o") Format Specifier.
DateTime 值:DateTime values:

2009-06-15T13:45:30 (DateTimeKind.Local) --> 2009-06-15T13:45:30.0000000-07:002009-06-15T13:45:30 (DateTimeKind.Local) --> 2009-06-15T13:45:30.0000000-07:00

2009-06-15T13:45:30 (DateTimeKind.Utc) --> 2009-06-15T13:45:30.0000000Z2009-06-15T13:45:30 (DateTimeKind.Utc) --> 2009-06-15T13:45:30.0000000Z

2009-06-15T13:45:30 (DateTimeKind.Unspecified) --> 2009-06-15T13:45:30.00000002009-06-15T13:45:30 (DateTimeKind.Unspecified) --> 2009-06-15T13:45:30.0000000

DateTimeOffset 值:DateTimeOffset values:

2009-06-15T13:45:30-07:00 --> 2009-06-15T13:45:30.0000000-07:002009-06-15T13:45:30-07:00 --> 2009-06-15T13:45:30.0000000-07:00
“R”、“r”"R", "r" RFC1123 模式。RFC1123 pattern.

更多信息:RFC1123(“R”、“r”)格式说明符More information: The RFC1123 ("R", "r") Format Specifier.
2009-06-15T13:45:30 -> Mon, 15 Jun 2009 20:45:30 GMT2009-06-15T13:45:30 -> Mon, 15 Jun 2009 20:45:30 GMT
“s”"s" 可排序日期/时间模式。Sortable date/time pattern.

更多信息:可排序(“s”)格式说明符More information: The Sortable ("s") Format Specifier.
2009-06-15T13:45:30 (DateTimeKind.Local) -> 2009-06-15T13:45:302009-06-15T13:45:30 (DateTimeKind.Local) -> 2009-06-15T13:45:30

2009-06-15T13:45:30 (DateTimeKind.Utc) -> 2009-06-15T13:45:302009-06-15T13:45:30 (DateTimeKind.Utc) -> 2009-06-15T13:45:30
“t”"t" 短时间模式。Short time pattern.

更多信息:可排序(“s”)格式说明符More information: The Short Time ("t") Format Specifier.
2009-06-15T13:45:30 -> 1:45 PM (en-US)2009-06-15T13:45:30 -> 1:45 PM (en-US)

2009-06-15T13:45:30 -> 13:45 (hr-HR)2009-06-15T13:45:30 -> 13:45 (hr-HR)

2009-06-15T13:45:30 -> 01:45 م (ar-EG)2009-06-15T13:45:30 -> 01:45 م (ar-EG)
“T”"T" 长时间模式。Long time pattern.

更多信息:长时间(“T”)格式说明符More information: The Long Time ("T") Format Specifier.
2009-06-15T13:45:30 -> 1:45:30 PM (en-US)2009-06-15T13:45:30 -> 1:45:30 PM (en-US)

2009-06-15T13:45:30 -> 13:45:30 (hr-HR)2009-06-15T13:45:30 -> 13:45:30 (hr-HR)

2009-06-15T13:45:30 -> 01:45:30 م (ar-EG)2009-06-15T13:45:30 -> 01:45:30 م (ar-EG)
“u”"u" 通用可排序日期/时间模式。Universal sortable date/time pattern.

更多信息:通用可排序(“u”)格式说明符More information: The Universal Sortable ("u") Format Specifier.
带有 DateTime 值:2009-06-15T13:45:30 -> 2009-06-15 13:45:30ZWith a DateTime value: 2009-06-15T13:45:30 -> 2009-06-15 13:45:30Z

带有 DateTimeOffset 值:2009-06-15T13:45:30 -> 2009-06-15 20:45:30ZWith a DateTimeOffset value: 2009-06-15T13:45:30 -> 2009-06-15 20:45:30Z
“U”"U" 通用完整日期/时间模式。Universal full date/time pattern.

更多信息:通用完整(“U”)格式说明符More information: The Universal Full ("U") Format Specifier.
2009-06-15T13:45:30 -> Monday, June 15, 2009 8:45:30 PM (en-US)2009-06-15T13:45:30 -> Monday, June 15, 2009 8:45:30 PM (en-US)

2009-06-15T13:45:30 -> den 15 juni 2009 20:45:30 (sv-SE)2009-06-15T13:45:30 -> den 15 juni 2009 20:45:30 (sv-SE)

2009-06-15T13:45:30 -> Δευτέρα, 15 Ιουνίου 2009 8:45:30 μμ (el-GR)2009-06-15T13:45:30 -> Δευτέρα, 15 Ιουνίου 2009 8:45:30 μμ (el-GR)
“Y”、“y”"Y", "y" 年月模式。Year month pattern.

更多信息:年月(“Y”、“y”)格式说明符More information: The Year Month ("Y") Format Specifier.
2009-06-15T13:45:30 -> June, 2009 (en-US)2009-06-15T13:45:30 -> June, 2009 (en-US)

2009-06-15T13:45:30 -> juni 2009 (da-DK)2009-06-15T13:45:30 -> juni 2009 (da-DK)

2009-06-15T13:45:30 -> Juni 2009 (id-ID)2009-06-15T13:45:30 -> Juni 2009 (id-ID)
任何其他单个字符Any other single character 未知说明符。Unknown specifier. 引发运行时 FormatExceptionThrows a run-time FormatException.

标准格式字符串的工作原理How Standard Format Strings Work

在格式设置操作中,标准格式字符串只是自定义格式字符串的别名。In a formatting operation, a standard format string is simply an alias for a custom format string. 使用别名引用自定义格式字符串的优点是:尽管别名保持固定不变,自定义格式字符串自身也可以变化。The advantage of using an alias to refer to a custom format string is that, although the alias remains invariant, the custom format string itself can vary. 这很重要,因为日期和时间值的字符串表示形式通常会因区域性而异。This is important because the string representations of date and time values typically vary by culture. 例如,“d”标准格式字符串指示应使用短日期模式显示日期和时间值。For example, the "d" standard format string indicates that a date and time value is to be displayed using a short date pattern. 对于固定区域性,此模式为“MM/dd/yyyy”。For the invariant culture, this pattern is "MM/dd/yyyy". 对于 fr-FR 区域性,此模式为“dd/MM/yyyy”。For the fr-FR culture, it is "dd/MM/yyyy". 对于 ja-JP 区域性,此模式为“yyyy/MM/dd”。For the ja-JP culture, it is "yyyy/MM/dd".

如果格式设置操作中的标准格式字符串映射到某个特定区域性的自定义格式字符串,则应用程序可定义该特定区域性,并通过以下方式之一使用其自定义格式字符串:If a standard format string in a formatting operation maps to a particular culture's custom format string, your application can define the specific culture whose custom format strings are used in one of these ways:

  • 可使用默认的(或当前的)区域性。You can use the default (or current) culture. 下面的示例使用当前区域性的短日期格式显示日期。The following example displays a date using the current culture's short date format. 在此情况下,当前区域性为 en-US。In this case, the current culture is en-US.

    // Display using current (en-us) culture's short date format
    DateTime thisDate = new DateTime(2008, 3, 15);
    Console.WriteLine(thisDate.ToString("d"));           // Displays 3/15/2008
    
    ' Display using current (en-us) culture's short date format
    Dim thisDate As Date = #03/15/2008#
    Console.WriteLine(thisDate.ToString("d"))     ' Displays 3/15/2008
    
  • 可以传递一个表示区域性的 CultureInfo 对象,该区域性的格式设置将用于具有 IFormatProvider 参数的方法。You can pass a CultureInfo object representing the culture whose formatting is to be used to a method that has an IFormatProvider parameter. 下面的示例使用 pt-BR 区域性的短日期格式显示日期。The following example displays a date using the short date format of the pt-BR culture.

    // Display using pt-BR culture's short date format
    DateTime thisDate = new DateTime(2008, 3, 15);
    CultureInfo culture = new CultureInfo("pt-BR");      
    Console.WriteLine(thisDate.ToString("d", culture));  // Displays 15/3/2008
    
    ' Display using pt-BR culture's short date format
    Dim thisDate As Date = #03/15/2008#
    Dim culture As New CultureInfo("pt-BR")      
    Console.WriteLine(thisDate.ToString("d", culture))   ' Displays 15/3/2008
    
  • 可以传递一个 DateTimeFormatInfo 对象,该对象向具有 IFormatProvider 参数的方法提供格式设置信息。You can pass a DateTimeFormatInfo object that provides formatting information to a method that has an IFormatProvider parameter. 下面的示例使用 hr-HR 区域性的 DateTimeFormatInfo 对象中的短日期格式显示日期。The following example displays a date using the short date format from a DateTimeFormatInfo object for the hr-HR culture.

    // Display using date format information from hr-HR culture
    DateTime thisDate = new DateTime(2008, 3, 15);
    DateTimeFormatInfo fmt = (new CultureInfo("hr-HR")).DateTimeFormat;
    Console.WriteLine(thisDate.ToString("d", fmt));      // Displays 15.3.2008
    
    ' Display using date format information from hr-HR culture
    Dim thisDate As Date = #03/15/2008#
    Dim fmt As DateTimeFormatInfo = (New CultureInfo("hr-HR")).DateTimeFormat
    Console.WriteLine(thisDate.ToString("d", fmt))   ' Displays 15.3.2008
    

备注

有关自定义用于格式化日期和时间值的模式或字符串的信息,请参见 NumberFormatInfo 类主题。For information about customizing the patterns or strings used in formatting date and time values, see the NumberFormatInfo class topic.

某些情况下,标准格式字符串用作固定不变的较长自定义格式字符串的简便缩写。In some cases, the standard format string serves as a convenient abbreviation for a longer custom format string that is invariant. 有四个标准格式字符串属于这一类别:“O”(或“o”)、“R”(或“r”)、“s”和“u”。Four standard format strings fall into this category: "O" (or "o"), "R" (or "r"), "s", and "u". 这些字符串对应于由固定区域性定义的自定义格式字符串。These strings correspond to custom format strings defined by the invariant culture. 通过这些字符串得到的日期和时间值的字符串表示形式在各个区域性中都应是相同的。They produce string representations of date and time values that are intended to be identical across cultures. 下表提供了有关这四个标准日期和时间格式字符串的信息。The following table provides information on these four standard date and time format strings.

标准格式字符串Standard format string 由 DateTimeFormatInfo.InvariantInfo 属性定义Defined by DateTimeFormatInfo.InvariantInfo property 自定义格式字符串Custom format string
“O”或“o”"O" or "o" None yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffzzyyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffzz
“R”或“r”"R" or "r" RFC1123Pattern ddd, dd MMM yyyy HH':'mm':'ss 'GMT'ddd, dd MMM yyyy HH':'mm':'ss 'GMT'
“s”"s" SortableDateTimePattern yyyy'-'MM'-'dd'T'HH':'mm':'ssyyyy'-'MM'-'dd'T'HH':'mm':'ss
“u”"u" UniversalSortableDateTimePattern yyyy'-'MM'-'dd HH':'mm':'ss'Z'yyyy'-'MM'-'dd HH':'mm':'ss'Z'

通过 DateTime.ParseExactDateTimeOffset.ParseExact 方法,还可以在分析操作中使用标准格式字符串,这些方法需要输入字符串才能完全符合确保分析操作成功的特定模式。Standard format strings can also be used in parsing operations with the DateTime.ParseExact or DateTimeOffset.ParseExact methods, which require an input string to exactly conform to a particular pattern for the parse operation to succeed. 许多标准格式字符串都映射到多个自定义格式字符串,因此,可采用各种格式表示日期和时间值并且分析操作仍然会成功。Many standard format strings map to multiple custom format strings, so a date and time value can be represented in a variety of formats and the parse operation will still succeed. 通过调用 DateTimeFormatInfo.GetAllDateTimePatterns(Char) 方法,你可以确定与标准格式字符串对应的自定义格式字符串。You can determine the custom format string or strings that correspond to a standard format string by calling the DateTimeFormatInfo.GetAllDateTimePatterns(Char) method. 下面的示例显示了映射到“d”(短日期模式)标准格式字符串的自定义格式字符串。The following example displays the custom format strings that map to the "d" (short date pattern) standard format string.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      Console.WriteLine("'d' standard format string:");
      foreach (var customString in DateTimeFormatInfo.CurrentInfo.GetAllDateTimePatterns('d'))
          Console.WriteLine("   {0}", customString);
   }
}
// The example displays the following output:
//       'd' standard format string:
//          M/d/yyyy
//          M/d/yy
//          MM/dd/yy
//          MM/dd/yyyy
//          yy/MM/dd
//          yyyy-MM-dd
//          dd-MMM-yy
Imports System.Globalization

Module Example
   Public Sub Main()
      Console.WriteLine("'d' standard format string:")
      For Each customString In DateTimeFormatInfo.CurrentInfo.GetAllDateTimePatterns("d"c)
          Console.WriteLine("   {0}", customString)
      Next                                  
   End Sub
End Module
' The example displays the following output:
'    'd' standard format string:
'       M/d/yyyy
'       M/d/yy
'       MM/dd/yy
'       MM/dd/yyyy
'       yy/MM/dd
'       yyyy-MM-dd
'       dd-MMM-yy

以下几节描述了 DateTimeDateTimeOffset 值的标准格式说明符。The following sections describe the standard format specifiers for DateTime and DateTimeOffset values.

短日期(“d”)格式说明符The Short Date ("d") Format Specifier

“d”标准格式说明符表示通过特定区域性的 DateTimeFormatInfo.ShortDatePattern 属性定义的自定义日期和时间格式字符串。The "d" standard format specifier represents a custom date and time format string that is defined by a specific culture's DateTimeFormatInfo.ShortDatePattern property. 例如,由固定区域性的 ShortDatePattern 属性返回的自定义格式字符串为“MM/dd/yyyy”。For example, the custom format string that is returned by the ShortDatePattern property of the invariant culture is "MM/dd/yyyy".

下表列出用于控制返回字符串格式的 DateTimeFormatInfo 对象属性。The following table lists the DateTimeFormatInfo object properties that control the formatting of the returned string.

属性Property 说明Description
ShortDatePattern 定义结果字符串的总体格式。Defines the overall format of the result string.
DateSeparator 定义用于分隔日期中年、月、日部分的字符串。Defines the string that separates the year, month, and day components of a date.

下面的示例使用“d”格式说明符来显示日期和时间值。The following example uses the "d" format specifier to display a date and time value.

DateTime date1 = new DateTime(2008,4, 10);
Console.WriteLine(date1.ToString("d", DateTimeFormatInfo.InvariantInfo));
// Displays 04/10/2008
Console.WriteLine(date1.ToString("d", 
                  CultureInfo.CreateSpecificCulture("en-US")));
// Displays 4/10/2008                       
Console.WriteLine(date1.ToString("d", 
                  CultureInfo.CreateSpecificCulture("en-NZ")));
// Displays 10/04/2008                       
Console.WriteLine(date1.ToString("d", 
                  CultureInfo.CreateSpecificCulture("de-DE")));
// Displays 10.04.2008                       
Dim date1 As Date = #4/10/2008#
Console.WriteLine(date1.ToString("d", DateTimeFormatInfo.InvariantInfo))
' Displays 04/10/2008
Console.WriteLine(date1.ToString("d", _
                  CultureInfo.CreateSpecificCulture("en-US")))
' Displays 4/10/2008                       
Console.WriteLine(date1.ToString("d", _
                  CultureInfo.CreateSpecificCulture("en-NZ")))
' Displays 10/04/2008                       
Console.WriteLine(date1.ToString("d", _
                  CultureInfo.CreateSpecificCulture("de-DE")))
' Displays 10.04.2008                       

返回表首Back to table

长日期(“D”)格式说明符The Long Date ("D") Format Specifier

“D”标准格式说明符表示由当前的 DateTimeFormatInfo.LongDatePattern 属性定义的自定义日期和时间格式字符串。The "D" standard format specifier represents a custom date and time format string that is defined by the current DateTimeFormatInfo.LongDatePattern property. 例如,用于固定区域性的自定义格式字符串为“dddd, dd MMMM yyyy”。For example, the custom format string for the invariant culture is "dddd, dd MMMM yyyy".

下表列出了用于控制返回字符串格式的 DateTimeFormatInfo 对象的属性。The following table lists the properties of the DateTimeFormatInfo object that control the formatting of the returned string.

属性Property 说明Description
LongDatePattern 定义结果字符串的总体格式。Defines the overall format of the result string.
DayNames 定义可在结果字符串中出现的本地化日名称。Defines the localized day names that can appear in the result string.
MonthNames 定义可在结果字符串中出现的本地化月份名称。Defines the localized month names that can appear in the result string.

下面的示例使用“D”格式说明符来显示日期和时间值。The following example uses the "D" format specifier to display a date and time value.

DateTime date1 = new DateTime(2008, 4, 10);
Console.WriteLine(date1.ToString("D", 
                  CultureInfo.CreateSpecificCulture("en-US")));
// Displays Thursday, April 10, 2008                        
Console.WriteLine(date1.ToString("D", 
                  CultureInfo.CreateSpecificCulture("pt-BR")));
// Displays quinta-feira, 10 de abril de 2008                        
Console.WriteLine(date1.ToString("D", 
                  CultureInfo.CreateSpecificCulture("es-MX")));
// Displays jueves, 10 de abril de 2008                        
Dim date1 As Date = #4/10/2008#
Console.WriteLine(date1.ToString("D", _
                  CultureInfo.CreateSpecificCulture("en-US")))
' Displays Thursday, April 10, 2008                        
Console.WriteLine(date1.ToString("D", _
                  CultureInfo.CreateSpecificCulture("pt-BR")))
' Displays quinta-feira, 10 de abril de 2008                        
Console.WriteLine(date1.ToString("D", _
                  CultureInfo.CreateSpecificCulture("es-MX")))
' Displays jueves, 10 de abril de 2008                        

返回表首Back to table

完整日期短时间(“f”)格式说明符The Full Date Short Time ("f") Format Specifier

“f”标准格式说明符表示长日期(“D”)和短时间(“t”)模式的组合,由空格分隔。The "f" standard format specifier represents a combination of the long date ("D") and short time ("t") patterns, separated by a space.

结果字符串受特定 DateTimeFormatInfo 对象的格式信息的影响。The result string is affected by the formatting information of a specific DateTimeFormatInfo object. 下表列出了 DateTimeFormatInfo 对象属性,这些属性可控制返回字符串的格式。The following table lists the DateTimeFormatInfo object properties that may control the formatting of the returned string. 由某些区域性的 DateTimeFormatInfo.LongDatePatternDateTimeFormatInfo.ShortTimePattern 属性返回的自定义格式说明符可能未利用所有属性。The custom format specifier returned by the DateTimeFormatInfo.LongDatePattern and DateTimeFormatInfo.ShortTimePattern properties of some cultures may not make use of all properties.

属性Property 说明Description
LongDatePattern 定义结果字符串中日期部分的格式。Defines the format of the date component of the result string.
ShortTimePattern 定义结果字符串中时间部分的格式。Defines the format of the time component of the result string.
DayNames 定义可在结果字符串中出现的本地化日名称。Defines the localized day names that can appear in the result string.
MonthNames 定义可在结果字符串中出现的本地化月份名称。Defines the localized month names that can appear in the result string.
TimeSeparator 定义分隔时间中小时、分钟和秒钟几个组成部分的字符串。Defines the string that separates the hour, minute, and second components of a time.
AMDesignator 定义以 12 小时时钟制表示午夜至正午之前这段时间的字符串。Defines the string that indicates times from midnight to before noon in a 12-hour clock.
PMDesignator 定义以 12 小时时钟制表示正午至午夜之前这段时间的字符串。Defines the string that indicates times from noon to before midnight in a 12-hour clock.

下面的示例使用“f”格式说明符来显示日期和时间值。The following example uses the "f" format specifier to display a date and time value.

DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);
Console.WriteLine(date1.ToString("f", 
                  CultureInfo.CreateSpecificCulture("en-US")));
// Displays Thursday, April 10, 2008 6:30 AM                        
Console.WriteLine(date1.ToString("f", 
                  CultureInfo.CreateSpecificCulture("fr-FR")));
// Displays jeudi 10 avril 2008 06:30                       
Dim date1 As Date = #4/10/2008 6:30AM#
Console.WriteLine(date1.ToString("f", _
                  CultureInfo.CreateSpecificCulture("en-US")))
' Displays Thursday, April 10, 2008 6:30 AM                        
Console.WriteLine(date1.ToString("f", _
                  CultureInfo.CreateSpecificCulture("fr-FR")))
' Displays jeudi 10 avril 2008 06:30                       

返回表首Back to table

完整日期长时间(“F”)格式说明符The Full Date Long Time ("F") Format Specifier

“F”标准格式说明符表示由当前的 DateTimeFormatInfo.FullDateTimePattern 属性定义的自定义日期和时间格式字符串。The "F" standard format specifier represents a custom date and time format string that is defined by the current DateTimeFormatInfo.FullDateTimePattern property. 例如,用于固定区域性的自定义格式字符串为“dddd, dd MMMM yyyy HH:mm:ss”。For example, the custom format string for the invariant culture is "dddd, dd MMMM yyyy HH:mm:ss".

下表列出了 DateTimeFormatInfo 对象属性,这些属性可控制返回字符串的格式。The following table lists the DateTimeFormatInfo object properties that may control the formatting of the returned string. 由某些区域性的 FullDateTimePattern 属性返回的自定义格式说明符可能未利用所有属性。The custom format specifier that is returned by the FullDateTimePattern property of some cultures may not make use of all properties.

属性Property 说明Description
FullDateTimePattern 定义结果字符串的总体格式。Defines the overall format of the result string.
DayNames 定义可在结果字符串中出现的本地化日名称。Defines the localized day names that can appear in the result string.
MonthNames 定义可在结果字符串中出现的本地化月份名称。Defines the localized month names that can appear in the result string.
TimeSeparator 定义分隔时间中小时、分钟和秒钟几个组成部分的字符串。Defines the string that separates the hour, minute, and second components of a time.
AMDesignator 定义以 12 小时时钟制表示午夜至正午之前这段时间的字符串。Defines the string that indicates times from midnight to before noon in a 12-hour clock.
PMDesignator 定义以 12 小时时钟制表示正午至午夜之前这段时间的字符串。Defines the string that indicates times from noon to before midnight in a 12-hour clock.

下面的示例使用“F”格式说明符来显示日期和时间值。The following example uses the "F" format specifier to display a date and time value.

DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);
Console.WriteLine(date1.ToString("F", 
                  CultureInfo.CreateSpecificCulture("en-US")));
// Displays Thursday, April 10, 2008 6:30:00 AM                        
Console.WriteLine(date1.ToString("F", 
                  CultureInfo.CreateSpecificCulture("fr-FR")));
// Displays jeudi 10 avril 2008 06:30:00                       
Dim date1 As Date = #4/10/2008 6:30AM#
Console.WriteLine(date1.ToString("F", _
                  CultureInfo.CreateSpecificCulture("en-US")))
' Displays Thursday, April 10, 2008 6:30:00 AM                        
Console.WriteLine(date1.ToString("F", _
                  CultureInfo.CreateSpecificCulture("fr-FR")))
' Displays jeudi 10 avril 2008 06:30:00                       

返回表首Back to table

常规日期短时间(“g”)格式说明符The General Date Short Time ("g") Format Specifier

“g”标准格式说明符表示短日期(“d”)和短时间(“t”)模式的组合,由空格分隔。The "g" standard format specifier represents a combination of the short date ("d") and short time ("t") patterns, separated by a space.

结果字符串受特定 DateTimeFormatInfo 对象的格式信息的影响。The result string is affected by the formatting information of a specific DateTimeFormatInfo object. 下表列出了 DateTimeFormatInfo 对象属性,这些属性可控制返回字符串的格式。The following table lists the DateTimeFormatInfo object properties that may control the formatting of the returned string. 由某些区域性的 DateTimeFormatInfo.ShortDatePatternDateTimeFormatInfo.ShortTimePattern 属性返回的自定义格式说明符可能未利用所有属性。The custom format specifier that is returned by the DateTimeFormatInfo.ShortDatePattern and DateTimeFormatInfo.ShortTimePattern properties of some cultures may not make use of all properties.

属性Property 说明Description
ShortDatePattern 定义结果字符串中日期部分的格式。Defines the format of the date component of the result string.
ShortTimePattern 定义结果字符串中时间部分的格式。Defines the format of the time component of the result string.
DateSeparator 定义用于分隔日期中年、月、日部分的字符串。Defines the string that separates the year, month, and day components of a date.
TimeSeparator 定义分隔时间中小时、分钟和秒钟几个组成部分的字符串。Defines the string that separates the hour, minute, and second components of a time.
AMDesignator 定义以 12 小时时钟制表示午夜至正午之前这段时间的字符串。Defines the string that indicates times from midnight to before noon in a 12-hour clock.
PMDesignator 定义以 12 小时时钟制表示正午至午夜之前这段时间的字符串。Defines the string that indicates times from noon to before midnight in a 12-hour clock.

下面的示例使用“g”格式说明符来显示日期和时间值。The following example uses the "g" format specifier to display a date and time value.

DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);
Console.WriteLine(date1.ToString("g", 
                  DateTimeFormatInfo.InvariantInfo));
// Displays 04/10/2008 06:30                      
Console.WriteLine(date1.ToString("g", 
                  CultureInfo.CreateSpecificCulture("en-us")));
// Displays 4/10/2008 6:30 AM                       
Console.WriteLine(date1.ToString("g", 
                  CultureInfo.CreateSpecificCulture("fr-BE")));
// Displays 10/04/2008 6:30                        
Dim date1 As Date = #4/10/2008 6:30AM#
Console.WriteLine(date1.ToString("g", _
                  DateTimeFormatInfo.InvariantInfo))
' Displays 04/10/2008 06:30                      
Console.WriteLine(date1.ToString("g", _
                  CultureInfo.CreateSpecificCulture("en-us")))
' Displays 4/10/2008 6:30 AM                       
Console.WriteLine(date1.ToString("g", _
                  CultureInfo.CreateSpecificCulture("fr-BE")))
' Displays 10/04/2008 6:30                        

返回表首Back to table

常规日期长时间(“G”)格式说明符The General Date Long Time ("G") Format Specifier

“G”标准格式说明符表示短日期(“d”)和长时间(“T”)模式的组合,由空格分隔。The "G" standard format specifier represents a combination of the short date ("d") and long time ("T") patterns, separated by a space.

结果字符串受特定 DateTimeFormatInfo 对象的格式信息的影响。The result string is affected by the formatting information of a specific DateTimeFormatInfo object. 下表列出了 DateTimeFormatInfo 对象属性,这些属性可控制返回字符串的格式。The following table lists the DateTimeFormatInfo object properties that may control the formatting of the returned string. 由某些区域性的 DateTimeFormatInfo.ShortDatePatternDateTimeFormatInfo.LongTimePattern 属性返回的自定义格式说明符可能未利用所有属性。The custom format specifier that is returned by the DateTimeFormatInfo.ShortDatePattern and DateTimeFormatInfo.LongTimePattern properties of some cultures may not make use of all properties.

属性Property 说明Description
ShortDatePattern 定义结果字符串中日期部分的格式。Defines the format of the date component of the result string.
LongTimePattern 定义结果字符串中时间部分的格式。Defines the format of the time component of the result string.
DateSeparator 定义用于分隔日期中年、月、日部分的字符串。Defines the string that separates the year, month, and day components of a date.
TimeSeparator 定义分隔时间中小时、分钟和秒钟几个组成部分的字符串。Defines the string that separates the hour, minute, and second components of a time.
AMDesignator 定义以 12 小时时钟制表示午夜至正午之前这段时间的字符串。Defines the string that indicates times from midnight to before noon in a 12-hour clock.
PMDesignator 定义以 12 小时时钟制表示正午至午夜之前这段时间的字符串。Defines the string that indicates times from noon to before midnight in a 12-hour clock.

下面的示例使用“G”格式说明符来显示日期和时间值。The following example uses the "G" format specifier to display a date and time value.

DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);
Console.WriteLine(date1.ToString("G", 
                  DateTimeFormatInfo.InvariantInfo));
// Displays 04/10/2008 06:30:00
Console.WriteLine(date1.ToString("G", 
                  CultureInfo.CreateSpecificCulture("en-us")));
// Displays 4/10/2008 6:30:00 AM                        
Console.WriteLine(date1.ToString("G", 
                  CultureInfo.CreateSpecificCulture("nl-BE")));
// Displays 10/04/2008 6:30:00                       
Dim date1 As Date = #4/10/2008 6:30AM#
Console.WriteLine(date1.ToString("G", _
                  DateTimeFormatInfo.InvariantInfo))
' Displays 04/10/2008 06:30:00
Console.WriteLine(date1.ToString("G", _
                  CultureInfo.CreateSpecificCulture("en-us")))
' Displays 4/10/2008 6:30:00 AM                        
Console.WriteLine(date1.ToString("G", _
                  CultureInfo.CreateSpecificCulture("nl-BE")))
' Displays 10/04/2008 6:30:00                       

返回表首Back to table

月(“M”、“m”)格式说明符The Month ("M", "m") Format Specifier

“M”或“m”标准格式说明符表示由当前的 DateTimeFormatInfo.MonthDayPattern 属性定义的自定义日期和时间格式字符串。The "M" or "m" standard format specifier represents a custom date and time format string that is defined by the current DateTimeFormatInfo.MonthDayPattern property. 例如,用于固定区域性的自定义格式字符串为“MMMM dd”。For example, the custom format string for the invariant culture is "MMMM dd".

下表列出用于控制返回字符串格式的 DateTimeFormatInfo 对象属性。The following table lists the DateTimeFormatInfo object properties that control the formatting of the returned string.

属性Property 说明Description
MonthDayPattern 定义结果字符串的总体格式。Defines the overall format of the result string.
MonthNames 定义可在结果字符串中出现的本地化月份名称。Defines the localized month names that can appear in the result string.

下面的示例使用“m”格式说明符来显示日期和时间值。The following example uses the "m" format specifier to display a date and time value.

DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);
Console.WriteLine(date1.ToString("m", 
                  CultureInfo.CreateSpecificCulture("en-us")));
// Displays April 10                        
Console.WriteLine(date1.ToString("m", 
                  CultureInfo.CreateSpecificCulture("ms-MY")));
// Displays 10 April                       
Dim date1 As Date = #4/10/2008 6:30AM#
Console.WriteLine(date1.ToString("m", _
                  CultureInfo.CreateSpecificCulture("en-us")))
' Displays April 10                        
Console.WriteLine(date1.ToString("m", _
                  CultureInfo.CreateSpecificCulture("ms-MY")))
' Displays 10 April                       

返回表首Back to table

往返(“O”、“o”)格式说明符The Round-trip ("O", "o") Format Specifier

“O”或“o”标准格式说明符表示使用保留时区信息的模式的自定义日期和时间格式字符串,并发出符合 ISO8601 的结果字符串。The "O" or "o" standard format specifier represents a custom date and time format string using a pattern that preserves time zone information and emits a result string that complies with ISO 8601. 对于 DateTime 值,此格式说明符设计用于在文本中将日期和时间值与 DateTime.Kind 属性一起保留。For DateTime values, this format specifier is designed to preserve date and time values along with the DateTime.Kind property in text. 如果将 DateTime.Parse(String, IFormatProvider, DateTimeStyles) 参数设置为 DateTime.ParseExact,则可通过使用 stylesDateTimeStyles.RoundtripKind 方法对设置了格式的字符串进行反向分析。The formatted string can be parsed back by using the DateTime.Parse(String, IFormatProvider, DateTimeStyles) or DateTime.ParseExact method if the styles parameter is set to DateTimeStyles.RoundtripKind.

对于 DateTime 值,“O”或“o”标准格式说明符对应于“yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK”自定义格式字符串,对于 DateTimeOffset 值,“O”或“o”标准格式说明符则对应于“yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffzzz”自定义格式字符串。The "O" or "o" standard format specifier corresponds to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" custom format string for DateTime values and to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffzzz" custom format string for DateTimeOffset values. 在此字符串中,分隔各个字符(例如连字符、冒号和字母“T”)的单引号标记对指示各个字符是不能更改的文本。In this string, the pairs of single quotation marks that delimit individual characters, such as the hyphens, the colons, and the letter "T", indicate that the individual character is a literal that cannot be changed. 撇号不会出现在输出字符串中。The apostrophes do not appear in the output string.

"O" 或 "o" 标准格式说明符(和 "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" 自定义格式字符串)利用 ISO 8601 表示时区信息的三种方式,从而暂留 DateTime 值的 Kind 属性:The "O" or "o" standard format specifier (and the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" custom format string) takes advantage of the three ways that ISO 8601 represents time zone information to preserve the Kind property of DateTime values:

  • DateTimeKind.Local 日期和时间值的时区组件是相对于 UTC 的偏移量(例如,+01:00,-07:00)。The time zone component of DateTimeKind.Local date and time values is an offset from UTC (for example, +01:00, -07:00). 所有 DateTimeOffset 值也以这种格式表示。All DateTimeOffset values are also represented in this format.

  • DateTimeKind.Utc 日期和时间值的时区组件使用“Z”(它代表零偏移量)以表示 UTC。The time zone component of DateTimeKind.Utc date and time values uses "Z" (which stands for zero offset) to represent UTC.

  • DateTimeKind.Unspecified 日期和时间值没有时区信息。DateTimeKind.Unspecified date and time values have no time zone information.

由于“O”或“o”标准格式说明符遵循国际标准,使用说明符的格式设置或分析操作始终使用固定区域性和公历。Because the "O" or "o" standard format specifier conforms to an international standard, the formatting or parsing operation that uses the specifier always uses the invariant culture and the Gregorian calendar.

如果字符串采用了这些格式中的某个格式,则可以通过使用“O”或“o”格式说明符分析传递到 ParseTryParseParseExactTryParseExactDateTimeDateTimeOffset 方法的这些字符串。Strings that are passed to the Parse, TryParse, ParseExact, and TryParseExact methods of DateTime and DateTimeOffset can be parsed by using the "O" or "o" format specifier if they are in one of these formats. 对于 DateTime 对象,你调用的分析重载还应当包含带有 styles 值的 DateTimeStyles.RoundtripKind 参数。In the case of DateTime objects, the parsing overload that you call should also include a styles parameter with a value of DateTimeStyles.RoundtripKind. 请注意,如果你使用对应于“O”或“o”格式说明符的自定义格式字符串调用分析方法,则你不会获得与“O”或“o”相同的结果。Note that if you call a parsing method with the custom format string that corresponds to the "O" or "o" format specifier, you won't get the same results as "O" or "o". 这是因为使用自定义格式字符串的分析方法不能分析缺少时区组件的日期和时间值的字符串表示形式,或使用“Z”指示 UTC。This is because parsing methods that use a custom format string can't parse the string representation of date and time values that lack a time zone component or use "Z" to indicate UTC.

下面的示例使用“o”格式说明符在美国太平洋时区中的系统上显示一系列 DateTime 值和 DateTimeOffset 值。The following example uses the "o" format specifier to display a series of DateTime values and a DateTimeOffset value on a system in the U.S. Pacific Time zone.

using System;

public class Example
{
   public static void Main()
   {
       DateTime dat = new DateTime(2009, 6, 15, 13, 45, 30, 
                                   DateTimeKind.Unspecified);
       Console.WriteLine("{0} ({1}) --> {0:O}", dat, dat.Kind); 
   
       DateTime uDat = new DateTime(2009, 6, 15, 13, 45, 30, 
                                    DateTimeKind.Utc);
       Console.WriteLine("{0} ({1}) --> {0:O}", uDat, uDat.Kind);
       
       DateTime lDat = new DateTime(2009, 6, 15, 13, 45, 30, 
                                    DateTimeKind.Local);
       Console.WriteLine("{0} ({1}) --> {0:O}\n", lDat, lDat.Kind);
       
       DateTimeOffset dto = new DateTimeOffset(lDat);
       Console.WriteLine("{0} --> {0:O}", dto);
   }
}
// The example displays the following output:
//    6/15/2009 1:45:30 PM (Unspecified) --> 2009-06-15T13:45:30.0000000
//    6/15/2009 1:45:30 PM (Utc) --> 2009-06-15T13:45:30.0000000Z
//    6/15/2009 1:45:30 PM (Local) --> 2009-06-15T13:45:30.0000000-07:00
//    
//    6/15/2009 1:45:30 PM -07:00 --> 2009-06-15T13:45:30.0000000-07:00
Module Example
   Public Sub Main()
       Dim dat As New Date(2009, 6, 15, 13, 45, 30, 
                           DateTimeKind.Unspecified)
       Console.WriteLine("{0} ({1}) --> {0:O}", dat, dat.Kind) 
   
       Dim uDat As New Date(2009, 6, 15, 13, 45, 30, DateTimeKind.Utc)
       Console.WriteLine("{0} ({1}) --> {0:O}", uDat, uDat.Kind)
       
       Dim lDat As New Date(2009, 6, 15, 13, 45, 30, DateTimeKind.Local)
       Console.WriteLine("{0} ({1}) --> {0:O}", lDat, lDat.Kind)
       Console.WriteLine()
       
       Dim dto As New DateTimeOffset(lDat)
       Console.WriteLine("{0} --> {0:O}", dto)
   End Sub
End Module
' The example displays the following output:
'    6/15/2009 1:45:30 PM (Unspecified) --> 2009-06-15T13:45:30.0000000
'    6/15/2009 1:45:30 PM (Utc) --> 2009-06-15T13:45:30.0000000Z
'    6/15/2009 1:45:30 PM (Local) --> 2009-06-15T13:45:30.0000000-07:00
'    
'    6/15/2009 1:45:30 PM -07:00 --> 2009-06-15T13:45:30.0000000-07:00

下面的示例使用“O”格式说明符创建格式字符串,然后通过调用日期和时间 Parse 方法还原原始日期和时间值。The following example uses the "o" format specifier to create a formatted string, and then restores the original date and time value by calling a date and time Parse method.

// Round-trip DateTime values.
DateTime originalDate, newDate;
string dateString;
// Round-trip a local time.
originalDate = DateTime.SpecifyKind(new DateTime(2008, 4, 10, 6, 30, 0), DateTimeKind.Local);
dateString = originalDate.ToString("o");
newDate = DateTime.Parse(dateString, null, DateTimeStyles.RoundtripKind);
Console.WriteLine("Round-tripped {0} {1} to {2} {3}.", originalDate, originalDate.Kind, 
                  newDate, newDate.Kind);
// Round-trip a UTC time.
originalDate = DateTime.SpecifyKind(new DateTime(2008, 4, 12, 9, 30, 0), DateTimeKind.Utc);                  
dateString = originalDate.ToString("o");
newDate = DateTime.Parse(dateString, null, DateTimeStyles.RoundtripKind);
Console.WriteLine("Round-tripped {0} {1} to {2} {3}.", originalDate, originalDate.Kind, 
                  newDate, newDate.Kind);
// Round-trip time in an unspecified time zone.
originalDate = DateTime.SpecifyKind(new DateTime(2008, 4, 13, 12, 30, 0), DateTimeKind.Unspecified);                  
dateString = originalDate.ToString("o");
newDate = DateTime.Parse(dateString, null, DateTimeStyles.RoundtripKind);
Console.WriteLine("Round-tripped {0} {1} to {2} {3}.", originalDate, originalDate.Kind, 
                  newDate, newDate.Kind);

// Round-trip a DateTimeOffset value.
DateTimeOffset originalDTO = new DateTimeOffset(2008, 4, 12, 9, 30, 0, new TimeSpan(-8, 0, 0));
dateString = originalDTO.ToString("o");
DateTimeOffset newDTO = DateTimeOffset.Parse(dateString, null, DateTimeStyles.RoundtripKind);
Console.WriteLine("Round-tripped {0} to {1}.", originalDTO, newDTO);
// The example displays the following output:
//    Round-tripped 4/10/2008 6:30:00 AM Local to 4/10/2008 6:30:00 AM Local.
//    Round-tripped 4/12/2008 9:30:00 AM Utc to 4/12/2008 9:30:00 AM Utc.
//    Round-tripped 4/13/2008 12:30:00 PM Unspecified to 4/13/2008 12:30:00 PM Unspecified.
//    Round-tripped 4/12/2008 9:30:00 AM -08:00 to 4/12/2008 9:30:00 AM -08:00.
' Round-trip DateTime values.
Dim originalDate, newDate As Date
Dim dateString As String
' Round-trip a local time.
originalDate = Date.SpecifyKind(#4/10/2008 6:30AM#, DateTimeKind.Local)
dateString = originalDate.ToString("o")
newDate = Date.Parse(dateString, Nothing, DateTimeStyles.RoundtripKind)
Console.WriteLine("Round-tripped {0} {1} to {2} {3}.", originalDate, originalDate.Kind, _
                  newDate, newDate.Kind)
' Round-trip a UTC time.
originalDate = Date.SpecifyKind(#4/12/2008 9:30AM#, DateTimeKind.Utc)                  
dateString = originalDate.ToString("o")
newDate = Date.Parse(dateString, Nothing, DateTimeStyles.RoundtripKind)
Console.WriteLine("Round-tripped {0} {1} to {2} {3}.", originalDate, originalDate.Kind, _
                  newDate, newDate.Kind)
' Round-trip time in an unspecified time zone.
originalDate = Date.SpecifyKind(#4/13/2008 12:30PM#, DateTimeKind.Unspecified)                  
dateString = originalDate.ToString("o")
newDate = Date.Parse(dateString, Nothing, DateTimeStyles.RoundtripKind)
Console.WriteLine("Round-tripped {0} {1} to {2} {3}.", originalDate, originalDate.Kind, _
                  newDate, newDate.Kind)

' Round-trip a DateTimeOffset value.
Dim originalDTO As New DateTimeOffset(#4/12/2008 9:30AM#, New TimeSpan(-8, 0, 0))
dateString = originalDTO.ToString("o")
Dim newDTO As DateTimeOffset = DateTimeOffset.Parse(dateString, Nothing, DateTimeStyles.RoundtripKind)
Console.WriteLine("Round-tripped {0} to {1}.", originalDTO, newDTO)
' The example displays the following output:
'    Round-tripped 4/10/2008 6:30:00 AM Local to 4/10/2008 6:30:00 AM Local.
'    Round-tripped 4/12/2008 9:30:00 AM Utc to 4/12/2008 9:30:00 AM Utc.
'    Round-tripped 4/13/2008 12:30:00 PM Unspecified to 4/13/2008 12:30:00 PM Unspecified.
'    Round-tripped 4/12/2008 9:30:00 AM -08:00 to 4/12/2008 9:30:00 AM -08:00.

返回表首Back to table

RFC1123(“R”、“r”)格式说明符The RFC1123 ("R", "r") Format Specifier

“R”或“r”标准格式说明符表示由 DateTimeFormatInfo.RFC1123Pattern 属性定义的自定义日期和时间格式字符串。The "R" or "r" standard format specifier represents a custom date and time format string that is defined by the DateTimeFormatInfo.RFC1123Pattern property. 该模式反映已定义的标准,并且属性是只读的。The pattern reflects a defined standard, and the property is read-only. 因此,无论所使用的区域性或所提供的格式提供程序是什么,它总是相同的。Therefore, it is always the same, regardless of the culture used or the format provider supplied. 定义格式字符串为“ddd, dd MMM yyyy HH':'mm':'ss 'GMT'”。The custom format string is "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'". 当使用此标准格式说明符时,格式设置或分析操作始终使用固定区域性。When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture.

结果字符串受由 DateTimeFormatInfo 属性(该属性表示固定区域性)返回的 DateTimeFormatInfo.InvariantInfo 对象的下列属性的影响。The result string is affected by the following properties of the DateTimeFormatInfo object returned by the DateTimeFormatInfo.InvariantInfo property that represents the invariant culture.

属性Property 说明Description
RFC1123Pattern 定义结果字符串的格式。Defines the format of the result string.
AbbreviatedDayNames 定义可在结果字符串中出现的缩写的日期名称。Defines the abbreviated day names that can appear in the result string.
AbbreviatedMonthNames 定义可在结果字符串中出现的缩写的月份名称。Defines the abbreviated month names that can appear in the result string.

尽管 RFC 1123 标准将时间表示为协调世界时 (UTC),格式设置操作也不会修改正在格式化的 DateTime 对象的值。Although the RFC 1123 standard expresses a time as Coordinated Universal Time (UTC), the formatting operation does not modify the value of the DateTime object that is being formatted. 因此,执行格式设置操作之前,必须通过调用 DateTime 方法将 DateTime.ToUniversalTime 值转换为 UTC。Therefore, you must convert the DateTime value to UTC by calling the DateTime.ToUniversalTime method before you perform the formatting operation. 相反,DateTimeOffset 值自动执行此转换;即执行格式设置操作之前无需调用 DateTimeOffset.ToUniversalTime 方法。In contrast, DateTimeOffset values perform this conversion automatically; there is no need to call the DateTimeOffset.ToUniversalTime method before the formatting operation.

下面的示例使用“r”格式说明符在美国太平洋时区中的系统上显示 DateTimeDateTimeOffset 值。The following example uses the "r" format specifier to display a DateTime and a DateTimeOffset value on a system in the U.S. Pacific Time zone.

DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);
DateTimeOffset dateOffset = new DateTimeOffset(date1, 
                            TimeZoneInfo.Local.GetUtcOffset(date1));
Console.WriteLine(date1.ToUniversalTime().ToString("r"));
// Displays Thu, 10 Apr 2008 13:30:00 GMT                       
Console.WriteLine(dateOffset.ToUniversalTime().ToString("r"));
// Displays Thu, 10 Apr 2008 13:30:00 GMT                        
Dim date1 As Date = #4/10/2008 6:30AM#
Dim dateOffset As New DateTimeOffset(date1, TimeZoneInfo.Local.GetUtcOFfset(date1))
Console.WriteLine(date1.ToUniversalTime.ToString("r"))
' Displays Thu, 10 Apr 2008 13:30:00 GMT                       
Console.WriteLine(dateOffset.ToUniversalTime.ToString("r"))
' Displays Thu, 10 Apr 2008 13:30:00 GMT                        

返回表首Back to table

可排序(“s”)格式说明符The Sortable ("s") Format Specifier

“s”标准格式说明符表示由 DateTimeFormatInfo.SortableDateTimePattern 属性定义的自定义日期和时间格式字符串。The "s" standard format specifier represents a custom date and time format string that is defined by the DateTimeFormatInfo.SortableDateTimePattern property. 该模式反映已定义的标准 (ISO 8601),并且属性是只读的。The pattern reflects a defined standard (ISO 8601), and the property is read-only. 因此,无论所使用的区域性或所提供的格式提供程序是什么,它总是相同的。Therefore, it is always the same, regardless of the culture used or the format provider supplied. 自定义格式字符串为“yyyy'-'MM'-'dd'T'HH':'mm':'ss”。The custom format string is "yyyy'-'MM'-'dd'T'HH':'mm':'ss".

使用“s”格式说明符的目的是使生成的结果字符串基于日期和时间值一致按升序或降序顺序进行排序。The purpose of the "s" format specifier is to produce result strings that sort consistently in ascending or descending order based on date and time values. 因此,尽管“s”标准格式说明符采用一致格式表示日期和时间值,但是格式化操作不会修改正在格式化以反映其 DateTime.Kind 属性或 DateTimeOffset.Offset 值的日期和时间对象的值。As a result, although the "s" standard format specifier represents a date and time value in a consistent format, the formatting operation does not modify the value of the date and time object that is being formatted to reflect its DateTime.Kind property or its DateTimeOffset.Offset value. 例如,通过格式化日期和时间值 2014-11-15T18:32:17+00:00 和 2014-11-15T18:32:17+08:00 生成的结果字符串完全相同。For example, the result strings produced by formatting the date and time values 2014-11-15T18:32:17+00:00 and 2014-11-15T18:32:17+08:00 are identical.

当使用此标准格式说明符时,格式设置或分析操作始终使用固定区域性。When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture.

下面的示例使用“s”格式说明符在美国太平洋时区中的系统上显示 DateTimeDateTimeOffset 值。The following example uses the "s" format specifier to display a DateTime and a DateTimeOffset value on a system in the U.S. Pacific Time zone.

DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);
Console.WriteLine(date1.ToString("s"));
// Displays 2008-04-10T06:30:00                       
Dim date1 As Date = #4/10/2008 6:30AM#
Console.WriteLine(date1.ToString("s"))
' Displays 2008-04-10T06:30:00                       

返回表首Back to table

短时间(“t”)格式说明符The Short Time ("t") Format Specifier

“t”标准格式说明符表示由当前的 DateTimeFormatInfo.ShortTimePattern 属性定义的自定义日期和时间格式字符串。The "t" standard format specifier represents a custom date and time format string that is defined by the current DateTimeFormatInfo.ShortTimePattern property. 例如,用于固定区域性的自定义格式字符串为“HH:mm”。For example, the custom format string for the invariant culture is "HH:mm".

结果字符串受特定 DateTimeFormatInfo 对象的格式信息的影响。The result string is affected by the formatting information of a specific DateTimeFormatInfo object. 下表列出了 DateTimeFormatInfo 对象属性,这些属性可控制返回字符串的格式。The following table lists the DateTimeFormatInfo object properties that may control the formatting of the returned string. 由某些区域性的 DateTimeFormatInfo.ShortTimePattern 属性返回的自定义格式说明符可能未利用所有属性。The custom format specifier that is returned by the DateTimeFormatInfo.ShortTimePattern property of some cultures may not make use of all properties.

属性Property 说明Description
ShortTimePattern 定义结果字符串中时间部分的格式。Defines the format of the time component of the result string.
TimeSeparator 定义分隔时间中小时、分钟和秒钟几个组成部分的字符串。Defines the string that separates the hour, minute, and second components of a time.
AMDesignator 定义以 12 小时时钟制表示午夜至正午之前这段时间的字符串。Defines the string that indicates times from midnight to before noon in a 12-hour clock.
PMDesignator 定义以 12 小时时钟制表示正午至午夜之前这段时间的字符串。Defines the string that indicates times from noon to before midnight in a 12-hour clock.

下面的示例使用“t”格式说明符来显示日期和时间值。The following example uses the "t" format specifier to display a date and time value.

DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);
Console.WriteLine(date1.ToString("t", 
                  CultureInfo.CreateSpecificCulture("en-us")));
// Displays 6:30 AM                        
Console.WriteLine(date1.ToString("t", 
                  CultureInfo.CreateSpecificCulture("es-ES")));
// Displays 6:30                      
Dim date1 As Date = #4/10/2008 6:30AM#
Console.WriteLine(date1.ToString("t", _
                  CultureInfo.CreateSpecificCulture("en-us")))
' Displays 6:30 AM                        
Console.WriteLine(date1.ToString("t", _
                  CultureInfo.CreateSpecificCulture("es-ES")))
' Displays 6:30                      

返回表首Back to table

长时间(“T”)格式说明符The Long Time ("T") Format Specifier

“T”标准格式说明符表示由特定区域性的 DateTimeFormatInfo.LongTimePattern 属性定义的自定义日期和时间格式字符串。The "T" standard format specifier represents a custom date and time format string that is defined by a specific culture's DateTimeFormatInfo.LongTimePattern property. 例如,用于固定区域性的自定义格式字符串为“HH:mm:ss”。For example, the custom format string for the invariant culture is "HH:mm:ss".

下表列出了 DateTimeFormatInfo 对象属性,这些属性可控制返回字符串的格式。The following table lists the DateTimeFormatInfo object properties that may control the formatting of the returned string. 由某些区域性的 DateTimeFormatInfo.LongTimePattern 属性返回的自定义格式说明符可能未利用所有属性。The custom format specifier that is returned by the DateTimeFormatInfo.LongTimePattern property of some cultures may not make use of all properties.

属性Property 说明Description
LongTimePattern 定义结果字符串中时间部分的格式。Defines the format of the time component of the result string.
TimeSeparator 定义分隔时间中小时、分钟和秒钟几个组成部分的字符串。Defines the string that separates the hour, minute, and second components of a time.
AMDesignator 定义以 12 小时时钟制表示午夜至正午之前这段时间的字符串。Defines the string that indicates times from midnight to before noon in a 12-hour clock.
PMDesignator 定义以 12 小时时钟制表示正午至午夜之前这段时间的字符串。Defines the string that indicates times from noon to before midnight in a 12-hour clock.

下面的示例使用“T”格式说明符来显示日期和时间值。The following example uses the "T" format specifier to display a date and time value.

DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);
Console.WriteLine(date1.ToString("T", 
                  CultureInfo.CreateSpecificCulture("en-us")));
// Displays 6:30:00 AM                       
Console.WriteLine(date1.ToString("T", 
                  CultureInfo.CreateSpecificCulture("es-ES")));
// Displays 6:30:00                      
Dim date1 As Date = #4/10/2008 6:30AM#
Console.WriteLine(date1.ToString("T", _
                  CultureInfo.CreateSpecificCulture("en-us")))
' Displays 6:30:00 AM                       
Console.WriteLine(date1.ToString("T", _
                  CultureInfo.CreateSpecificCulture("es-ES")))
' Displays 6:30:00                      

返回表首Back to table

通用可排序(“u”)格式说明符The Universal Sortable ("u") Format Specifier

“u”标准格式说明符表示由 DateTimeFormatInfo.UniversalSortableDateTimePattern 属性定义的自定义日期和时间格式字符串。The "u" standard format specifier represents a custom date and time format string that is defined by the DateTimeFormatInfo.UniversalSortableDateTimePattern property. 该模式反映已定义的标准,并且属性是只读的。The pattern reflects a defined standard, and the property is read-only. 因此,无论所使用的区域性或所提供的格式提供程序是什么,它总是相同的。Therefore, it is always the same, regardless of the culture used or the format provider supplied. 自定义格式字符串为“yyyy'-'MM'-'dd HH':'mm':'ss'Z'”。The custom format string is "yyyy'-'MM'-'dd HH':'mm':'ss'Z'". 当使用此标准格式说明符时,格式设置或分析操作始终使用固定区域性。When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture.

尽管结果字符串应将时间表达为协调世界时 (UTC),但在格式设置操作过程中不转换原始 DateTime 值。Although the result string should express a time as Coordinated Universal Time (UTC), no conversion of the original DateTime value is performed during the formatting operation. 因此,在对 DateTime 值进行格式设置之前,必须通过调用 DateTime.ToUniversalTime 方法将该值转换为 UTC。Therefore, you must convert a DateTime value to UTC by calling the DateTime.ToUniversalTime method before formatting it. 相反,DateTimeOffset 值自动执行此转换;即执行格式设置操作之前无需调用 DateTimeOffset.ToUniversalTime 方法。In contrast, DateTimeOffset values perform this conversion automatically; there is no need to call the DateTimeOffset.ToUniversalTime method before the formatting operation.

下面的示例使用“u”格式说明符来显示日期和时间值。The following example uses the "u" format specifier to display a date and time value.

DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);
Console.WriteLine(date1.ToUniversalTime().ToString("u"));
// Displays 2008-04-10 13:30:00Z                       
Dim date1 As Date = #4/10/2008 6:30AM#
Console.WriteLine(date1.ToUniversalTime.ToString("u"))
' Displays 2008-04-10 13:30:00Z                       

返回表首Back to table

通用完整(“U”)格式说明符The Universal Full ("U") Format Specifier

“U”标准格式说明符表示由特定区域性的 DateTimeFormatInfo.FullDateTimePattern 属性定义的自定义日期和时间格式字符串。The "U" standard format specifier represents a custom date and time format string that is defined by a specified culture's DateTimeFormatInfo.FullDateTimePattern property. 此模式与“F”模式相同。The pattern is the same as the "F" pattern. 但是,在对 DateTime 值进行格式设置之前,该值自动转换为 UTC。However, the DateTime value is automatically converted to UTC before it is formatted.

下表列出了 DateTimeFormatInfo 对象属性,这些属性可控制返回字符串的格式。The following table lists the DateTimeFormatInfo object properties that may control the formatting of the returned string. 由某些区域性的 FullDateTimePattern 属性返回的自定义格式说明符可能未利用所有属性。The custom format specifier that is returned by the FullDateTimePattern property of some cultures may not make use of all properties.

属性Property 说明Description
FullDateTimePattern 定义结果字符串的总体格式。Defines the overall format of the result string.
DayNames 定义可在结果字符串中出现的本地化日名称。Defines the localized day names that can appear in the result string.
MonthNames 定义可在结果字符串中出现的本地化月份名称。Defines the localized month names that can appear in the result string.
TimeSeparator 定义分隔时间中小时、分钟和秒钟几个组成部分的字符串。Defines the string that separates the hour, minute, and second components of a time.
AMDesignator 定义以 12 小时时钟制表示午夜至正午之前这段时间的字符串。Defines the string that indicates times from midnight to before noon in a 12-hour clock.
PMDesignator 定义以 12 小时时钟制表示正午至午夜之前这段时间的字符串。Defines the string that indicates times from noon to before midnight in a 12-hour clock.

DateTimeOffset 类型不支持“U”格式说明符。如果使用“U”格式说明符来设置 FormatException 值的格式,则将引发 DateTimeOffsetThe "U" format specifier is not supported by the DateTimeOffset type and throws a FormatException if it is used to format a DateTimeOffset value.

下面的示例使用“U”格式说明符来显示日期和时间值。The following example uses the "U" format specifier to display a date and time value.

DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);
Console.WriteLine(date1.ToString("U", 
                  CultureInfo.CreateSpecificCulture("en-US")));
// Displays Thursday, April 10, 2008 1:30:00 PM                       
Console.WriteLine(date1.ToString("U", 
                  CultureInfo.CreateSpecificCulture("sv-FI")));
// Displays den 10 april 2008 13:30:00                       
Dim date1 As Date = #4/10/2008 6:30AM#
Console.WriteLine(date1.ToString("U", CultureInfo.CreateSpecificCulture("en-US")))
' Displays Thursday, April 10, 2008 1:30:00 PM                       
Console.WriteLine(date1.ToString("U", CultureInfo.CreateSpecificCulture("sv-FI")))
' Displays den 10 april 2008 13:30:00                       

返回表首Back to table

年月(“Y”、“y”)格式说明符The Year Month ("Y", "y") Format Specifier

“Y”或“y”标准格式说明符表示由指定区域性的 DateTimeFormatInfo.YearMonthPattern 属性定义的自定义日期和时间格式字符串。The "Y" or "y" standard format specifier represents a custom date and time format string that is defined by the DateTimeFormatInfo.YearMonthPattern property of a specified culture. 例如,用于固定区域性的自定义格式字符串为“yyyy MMMM”。For example, the custom format string for the invariant culture is "yyyy MMMM".

下表列出用于控制返回字符串格式的 DateTimeFormatInfo 对象属性。The following table lists the DateTimeFormatInfo object properties that control the formatting of the returned string.

属性Property 说明Description
YearMonthPattern 定义结果字符串的总体格式。Defines the overall format of the result string.
MonthNames 定义可在结果字符串中出现的本地化月份名称。Defines the localized month names that can appear in the result string.

下面的示例使用“y”格式说明符来显示日期和时间值。The following example uses the "y" format specifier to display a date and time value.

DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);
Console.WriteLine(date1.ToString("Y", 
                  CultureInfo.CreateSpecificCulture("en-US")));
// Displays April, 2008                       
Console.WriteLine(date1.ToString("y", 
                  CultureInfo.CreateSpecificCulture("af-ZA")));
// Displays April 2008                       
Dim date1 As Date = #4/10/2008 6:30AM#
Console.WriteLine(date1.ToString("Y", CultureInfo.CreateSpecificCulture("en-US")))
' Displays April, 2008                       
Console.WriteLine(date1.ToString("y", CultureInfo.CreateSpecificCulture("af-ZA")))
' Displays April 2008                       

返回表首Back to table

说明Notes

控制面板设置Control Panel Settings

控制面板中 “区域和语言选项” 项中的设置会影响由格式化操作产生的结果字符串。The settings in the Regional and Language Options item in Control Panel influence the result string produced by a formatting operation. 这些设置用于初始化与当前线程区域性关联的 DateTimeFormatInfo 对象,当前线程区域性提供用于控制格式设置的值。These settings are used to initialize the DateTimeFormatInfo object associated with the current thread culture, which provides values used to govern formatting. 使用不同设置的计算机将生成不同的结果字符串。Computers that use different settings generate different result strings.

此外,如果使用 CultureInfo.CultureInfo(String) 构造函数实例化一个新的 CultureInfo 对象以表示与当前的系统区域性相同的区域性,则通过控制面板中的 “区域和语言选项” 建立的任何自定义都将应用到新的 CultureInfo 对象。In addition, if you use the CultureInfo.CultureInfo(String) constructor to instantiate a new CultureInfo object that represents the same culture as the current system culture, any customizations established by the Regional and Language Options item in Control Panel will be applied to the new CultureInfo object. 可以使用 CultureInfo.CultureInfo(String, Boolean) 构造函数来创建不会反映系统的自定义项的 CultureInfo 对象。You can use the CultureInfo.CultureInfo(String, Boolean) constructor to create a CultureInfo object that does not reflect a system's customizations.

DateTimeFormatInfo 属性DateTimeFormatInfo Properties

格式化受当前的 DateTimeFormatInfo 对象的属性影响,其由当前线程区域性隐式提供或由调用格式化的方法的 IFormatProvider 参数显式提供。Formatting is influenced by properties of the current DateTimeFormatInfo object, which is provided implicitly by the current thread culture or explicitly by the IFormatProvider parameter of the method that invokes formatting. 对于 IFormatProvider 参数,应用程序应指定一个表示区域性的 CultureInfo 对象或表示特定区域性的日期和时间格式设置约定的 DateTimeFormatInfo 对象。For the IFormatProvider parameter, your application should specify a CultureInfo object, which represents a culture, or a DateTimeFormatInfo object, which represents a particular culture's date and time formatting conventions. 许多标准日期和时间格式说明符是由当前的 DateTimeFormatInfo 对象的属性定义的格式设置模式的别名。Many of the standard date and time format specifiers are aliases for formatting patterns defined by properties of the current DateTimeFormatInfo object. 应用程序通过更改相应 DateTimeFormatInfo 属性的相应日期和时间格式模式,可以更改由某些标准日期和时间格式说明符产生的结果。Your application can change the result produced by some standard date and time format specifiers by changing the corresponding date and time format patterns of the corresponding DateTimeFormatInfo property.

请参阅See also