分析 .NET 中的日期和时间字符串Parsing Date and Time Strings in .NET

分析字符串以将其转换为 DateTime 对象需要你指定有关如何以文本格式表示日期和时间的信息。Parsing strings to convert them to DateTime objects requires you to specify information about how the dates and times are represented as text. 不同的区域性所使用的日、月和年的顺序也不尽相同。Different cultures use different orders for day, month, and year. 某些时间表示方法使用 24 小时制,其他时间表示方法则会指定“AM”和“PM”。Some time representations use a 24-hour clock, others specify "AM" and "PM." 某些应用程序仅需要日期。Some applications need only the date. 其他应用程序仅需要时间。Others need only the time. 还有其他应用程序需要同时指定日期和时间。Still others need to specify both the date and the time. 通过将字符串转换为 DateTime 对象的方法,你将能够提供有关你预期的格式和你的应用程序需要的日期和时间元素的详细信息。The methods that convert strings to DateTime objects enable you to provide detailed information about the formats you expect and the elements of a date and time your application needs. 将文本正确转换为 DateTime 需要执行三个子任务:There are three subtasks to correctly converting text into a DateTime:

  1. 必须指定表示日期和时间的文本的预期格式。You must specify the expected format of the text representing a date and time.
  2. 可以指定日期时间格式的区域性。You may specify the culture for the format of a date time.
  3. 可以指定如何以日期和时间格式设置文本表示方法中缺少的组成部分。You may specify how missing components in the text representation are set in the date and time.

ParseTryParse 方法可转换日期和时间的多个常见表示方法。The Parse and TryParse methods convert many common representations of a date and time. ParseExactTryParseExact 方法可转换符合日期和时间格式字符串指定的模式的字符串表示形式。The ParseExact and TryParseExact methods convert a string representation that conforms to the pattern specified by a date and time format string. (如需详细信息,请参阅有关标准日期和时间格式字符串自定义日期和时间格式字符串的文章。)(See the articles on standard date and time format strings and custom date and time format strings for details.)

当前的 DateTimeFormatInfo 对象提供对如何将文本解释为日期和时间的更好的控制。The current DateTimeFormatInfo object provides more control over how text should be interpreted as a date and time. DateTimeFormatInfo 的属性描述了日期和时间分隔符,以及月、日、年代的名称,还有“AM”和“PM”标志的格式。Properties of a DateTimeFormatInfo describe the date and time separators, and the names of months, days, and eras, and the format for the "AM" and "PM" designations. 当前线程区域性提供了表示当前区域性的 DateTimeFormatInfoThe current thread culture provides a DateTimeFormatInfo that represents the current culture. 如果你希望使用特定区域性或自定义设置,请指定分析方法的 IFormatProvider 参数。If you want a specific culture or custom settings, you specify the IFormatProvider parameter of a parsing method. 对于 IFormatProvider 参数,应指定表示区域性的 CultureInfo 对象,或指定 DateTimeFormatInfo 对象。For the IFormatProvider parameter, specify a CultureInfo object, which represents a culture, or a DateTimeFormatInfo object.

表示日期或时间的文本可能缺少某些信息。The text representing a date or time may be missing some information. 例如,大多数人都会假定“3 月 12 日”这个日期表示当前年份。For example, most people would assume the date "March 12" represents the current year. 同样,“2018 年 3 月”表示年份为 2018,月份为 3 月。Similarly, "March 2018" represents the month of March in the year 2018. 表示时间的文本通常仅包括小时、分钟和 AM/PM 标志。Text representing time often does only includes hours, minutes, and an AM/PM designation. 分析方法通过使用合理的默认值处理此类缺少的信息:Parsing methods handle this missing information by using reasonable defaults:

  • 当仅存在时间时,日期部分将使用当前日期。When only the time is present, the date portion uses the current date.
  • 当仅存在日期时,时间部分将是午夜。When only the date is present, the time portion is midnight.
  • 如果日期中未指定年份,则使用当前年份。When the year isn't specified in a date, the current year is used.
  • 如果未指定一个月中的第几天,则使用一个月中的第一天。When the day of the month isn't specified, the first of the month is used.

如果字符串中存在日期,则它必须包括月份、某日或某年。If the date is present in the string, it must include the month and one of the day or year. 如果存在时间,则它必须包括小时和分钟或 AM/PM 标志。If the time is present, it must include the hour, and either the minutes or the AM/PM designator.

你可以指定 NoCurrentDateDefault 常量,以覆盖这些默认值。You can specify the NoCurrentDateDefault constant to override these defaults. 使用该常量时,任何缺少的年、月或天属性将设置为值 1When you use that constant, any missing year, month, or day properties are set to the value 1. 使用 Parse最后一个示例对此行为进行了演示。The last example using Parse demonstrates this behavior.

除了日期和时间组成部分,日期和时间的字符串表示形式还可以包含指示时间与协调世界时 (UTC) 相差多少的偏移量。In addition to a date and a time component, the string representation of a date and time can include an offset that indicates how much the time differs from Coordinated Universal Time (UTC). 例如,字符串“2/14/2007 5:32:00 -7:00”定义比 UTC 早七个小时的时间。For example, the string "2/14/2007 5:32:00 -7:00" defines a time that is seven hours earlier than UTC. 如果在时间的字符串表示形式中省略了偏移,分析方法返回 DateTime 对象,它的 Kind 属性设置为 DateTimeKind.UnspecifiedIf an offset is omitted from the string representation of a time, parsing returns a DateTime object with its Kind property set to DateTimeKind.Unspecified. 如果指定了偏移,分析方法返回 DateTime 对象,它的 Kind 属性设置为 DateTimeKind.Local,且值调整为采用计算机的本地时区。If an offset is specified, parsing returns a DateTime object with its Kind property set to DateTimeKind.Local and its value adjusted to the local time zone of your machine. 可以通过结合使用 DateTimeStyles 值和分析方法来修改此行为。You can modify this behavior by using a DateTimeStyles value with the parsing method.

格式提供程序还用于解释不明确的数字日期。The format provider is also used to interpret an ambiguous numeric date. 不清楚字符串“02/03/04”所表示的日期的哪些组成部分是月、日和年。It is not clear which components of the date represented by the string "02/03/04" are the month, day, and year. 组成部分根据格式提供程序中相似日期格式的顺序进行解释。The components are interpreted according to the order of similar date formats in the format provider.

ParseParse

下面的示例说明了如何使用 DateTime.Parse 方法将 string 转换为 DateTimeThe following example illustrates the use of the DateTime.Parse method to convert a string into a DateTime. 此示例使用与当前线程关联的区域性。This example uses the culture associated with the current thread. 如果与当前区域性关联的 CultureInfo 无法分析输入字符串,则会抛出 FormatExceptionIf the CultureInfo associated with the current culture cannot parse the input string, a FormatException is thrown.

提示

本文中的所有 C# 示例均在你的浏览器中运行。All the C# samples in this article run in your browser. 按“运行” 按钮查看输出。Press the Run button to see the output. 你还可以对其进行编辑以自行实验。You can also edit them to experiment yourself.

备注

这些示例可在适用于 C#VB 的 GitHub 文档存储库中获取。These examples are available in the GitHub docs repo for both C# and VB. 或者你可以下载压缩文件形式的 C#VB 项目。Or you can download the project as a zipfile for C# or VB.

string dateInput = "Jan 1, 2009";
DateTime parsedDate = DateTime.Parse(dateInput);
Console.WriteLine(parsedDate);
// Displays the following output on a system whose culture is en-US:
//       1/1/2009 12:00:00 AM
Dim MyString As String = "Jan 1, 2009"
Dim MyDateTime As DateTime = DateTime.Parse(MyString)
Console.WriteLine(MyDateTime)
' Displays the following output on a system whose culture is en-US:
'       1/1/2009 12:00:00 AM

你也可以显式定义分析字符串时将使用其格式设置约定的区域性。You can also explicitly define the culture whose formatting conventions are used when you parse a string. 指定 CultureInfo.DateTimeFormat 属性返回的一个标准 DateTimeFormatInfo 对象。You specify one of the standard DateTimeFormatInfo objects returned by the CultureInfo.DateTimeFormat property. 下面的示例使用格式提供程序将德语字符串分析为 DateTimeThe following example uses a format provider to parse a German string into a DateTime. 它创建了一个表示 de-DE 区域性的 CultureInfoIt creates a CultureInfo representing the de-DE culture. CultureInfo 对象可以确保成功分析此特定的字符串。That CultureInfo object ensures successful parsing of this particular string. 这会排除处于 CurrentThreadCurrentCulture 中的任何设置。This precludes whatever setting is in the CurrentCulture of the CurrentThread.

CultureInfo MyCultureInfo = new CultureInfo("de-DE");
string MyString = "12 Juni 2008";
DateTime MyDateTime = DateTime.Parse(MyString, MyCultureInfo);
Console.WriteLine(MyDateTime);
// The example displays the following output:
//       6/12/2008 12:00:00 AM
Dim MyCultureInfo As CultureInfo = New CultureInfo("de-DE")
Dim MyString As String = "12 Juni 2008"
Dim MyDateTime As DateTime = DateTime.Parse(MyString, MyCultureInfo)
Console.WriteLine(MyDateTime)
' The example displays the following output:
'       6/12/2008 12:00:00 AM

不过,虽然可以使用 Parse 方法重载指定自定义格式提供程序,但此方法不支持分析非标准格式。However, although you can use overloads of the Parse method to specify custom format providers, the method does not support parsing non-standard formats. 若要分析非标准格式的日期和时间,请改用 ParseExact 方法。To parse a date and time expressed in a non-standard format, use the ParseExact method instead.

下面的示例使用 DateTimeStyles 枚举,指定不得将当前日期和时间信息添加到未指定字段的 DateTimeThe following example uses the DateTimeStyles enumeration to specify that the current date and time information should not be added to the DateTime for unspecified fields.

CultureInfo MyCultureInfo = new CultureInfo("de-DE");
string MyString = "12 Juni 2008";
DateTime MyDateTime = DateTime.Parse(MyString, MyCultureInfo,
                                     DateTimeStyles.NoCurrentDateDefault);
Console.WriteLine(MyDateTime);
// The example displays the following output if the current culture is en-US:
//      6/12/2008 12:00:00 AM
Dim MyCultureInfo As CultureInfo = New CultureInfo("de-DE")
Dim MyString As String = "12 Juni 2008"
Dim MyDateTime As DateTime = DateTime.Parse(MyString, MyCultureInfo,
                           DateTimeStyles.NoCurrentDateDefault)
Console.WriteLine(MyDateTime)
' The example displays the following output if the current culture is en-US:
'       6/12/2008 12:00:00 AM

ParseExactParseExact

DateTime.ParseExact 方法将符合其中一个指定字符串模式的字符串转换为 DateTime 对象。The DateTime.ParseExact method converts a string to a DateTime object if it conforms to one of the specified string patterns. 将未采用其中一种指定格式的字符串传递给此方法时,会引发 FormatExceptionWhen a string that is not one of the forms specified is passed to this method, a FormatException is thrown. 可以指定一种标准日期和时间格式说明符或自定义格式说明符的组合。You can specify one of the standard date and time format specifiers or a combination of the custom format specifiers. 使用自定义格式说明符可以构造自定义识别字符串。Using the custom format specifiers, it is possible for you to construct a custom recognition string. 有关说明符的说明,请参见有关标准日期和时间格式字符串自定义日期和时间格式字符串的主题。For an explanation of the specifiers, see the topics on standard date and time format strings and custom date and time format strings.

在下面的示例中,向 DateTime.ParseExact 方法传递了一个要分析的字符串对象,后跟一个格式说明符,再后跟一个 CultureInfo 对象。In the following example, the DateTime.ParseExact method is passed a string object to parse, followed by a format specifier, followed by a CultureInfo object. ParseExact 方法只能分析在 en-US 区域性中遵循长日期模式的字符串。This ParseExact method can only parse strings that follow the long date pattern in the en-US culture.

CultureInfo MyCultureInfo = new CultureInfo("en-US");
string[] MyString = { " Friday, April 10, 2009", "Friday, April 10, 2009" };
foreach (string dateString in MyString)
{
    try
    {
        DateTime MyDateTime = DateTime.ParseExact(dateString, "D", MyCultureInfo);
        Console.WriteLine(MyDateTime);
    }
    catch (FormatException)
    {
        Console.WriteLine("Unable to parse '{0}'", dateString);
    }
}
// The example displays the following output:
//       Unable to parse ' Friday, April 10, 2009'
//       4/10/2009 12:00:00 AM
Dim MyCultureInfo As CultureInfo = New CultureInfo("en-US")
Dim MyString() As String = {" Friday, April 10, 2009", "Friday, April 10, 2009"}
For Each dateString As String In MyString
    Try
        Dim MyDateTime As DateTime = DateTime.ParseExact(dateString, "D",
                                                     MyCultureInfo)
        Console.WriteLine(MyDateTime)
    Catch e As FormatException
        Console.WriteLine("Unable to parse '{0}'", dateString)
    End Try
Next
' The example displays the following output:
'       Unable to parse ' Friday, April 10, 2009'
'       4/10/2009 12:00:00 AM

ParseParseExact 方法的每个重载还包含 IFormatProvider 参数,用于提供有关字符串格式设置的区域性专用信息。Each overload of the Parse and ParseExact methods also has an IFormatProvider parameter that provides culture-specific information about the formatting of the string. IFormatProvider 对象为 CultureInfo 对象,表示标准区域性或 CultureInfo.DateTimeFormat 属性返回的 DateTimeFormatInfo 对象。This IFormatProvider object is a CultureInfo object that represents a standard culture or a DateTimeFormatInfo object that is returned by the CultureInfo.DateTimeFormat property. ParseExact 还使用定义一个或多个自定义日期和时间格式的其他字符串或字符串数组参数。ParseExact also uses an additional string or string array argument that defines one or more custom date and time formats.

请参阅See also