DateTime.Parse DateTime.Parse DateTime.Parse DateTime.Parse Method

定义

将日期和时间的字符串表示形式转换为其等效的 DateTimeConverts the string representation of a date and time to its DateTime equivalent.

重载

Parse(String) Parse(String) Parse(String) Parse(String)

使用当前线程区域性的约定将日期和时间的字符串表示形式转换为其等效的 DateTimeConverts the string representation of a date and time to its DateTime equivalent by using the conventions of the current thread culture.

Parse(String, IFormatProvider) Parse(String, IFormatProvider) Parse(String, IFormatProvider) Parse(String, IFormatProvider)

使用指定的区域性特定格式设置信息,将日期和时间的字符串表示形式转换为其等效的 DateTimeConverts the string representation of a date and time to its DateTime equivalent by using culture-specific format information.

Parse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles) Parse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles) Parse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles)

使用指定的区域性特定格式设置信息和格式类型,将包含日期和时间的字符串表示形式的内存范围转换为其等效的 DateTimeConverts a memory span that contains string representation of a date and time to its DateTime equivalent by using culture-specific format information and a formatting style.

Parse(String, IFormatProvider, DateTimeStyles) Parse(String, IFormatProvider, DateTimeStyles) Parse(String, IFormatProvider, DateTimeStyles) Parse(String, IFormatProvider, DateTimeStyles)

使用指定的区域性特定格式设置信息和格式类型,将日期和时间的字符串表示形式转换为其等效的 DateTimeConverts the string representation of a date and time to its DateTime equivalent by using culture-specific format information and a formatting style.

示例

调用 DateTime.Parse 方法的很多示例都在本文的 "备注" 部分和单个 DateTime.Parse 重载的文档中进行了分散。Numerous examples that call the DateTime.Parse method are interspersed throughout the Remarks section of this article and in the documentation for the individual DateTime.Parse overloads.

备注

本文中的一些 C# 示例运行在 Try.NET 内联代码运行程序和演练环境中。Some 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.

还可以从dotnet/samples GitHub 存储库下载包含在.net core 2.0 项目C# 中的一整套 DateTime.Parse 示例和用于 Visual Basic 的 .net core 2.0 项目You can also download a complete set of DateTime.Parse examples, which are included in a .NET Core 2.0 project for C# and a .NET Core 2.0 project for Visual Basic, from the dotnet/samples GitHub repository.

注解

本节内容:In this section:

我要调用哪种方法?Which method do I call?

功能To CallCall
使用当前区域性的约定分析日期和时间字符串。Parse a date and time string by using the conventions of the current culture. Parse(String) 重载Parse(String) overload
使用特定区域性的约定分析日期和时间字符串。Parse a date and time string by using the conventions of a specific culture. Parse(String, IFormatProvider) 重载(请参阅分析和文化约定Parse(String, IFormatProvider) overload (see Parsing and Cultural Conventions)
使用特殊的样式元素(如空格或无空格)分析日期和时间字符串。Parse a date and time string with special style elements (such as white space or no white space). Parse(String, IFormatProvider, DateTimeStyles) 重载Parse(String, IFormatProvider, DateTimeStyles) overload
分析日期和时间字符串,该字符串必须采用特定格式。Parse a date and time string that must be in a particular format. DateTime.ParseExactDateTime.TryParseExactDateTime.ParseExact or DateTime.TryParseExact
分析日期和时间字符串,并执行到 UTC 或本地时间的转换。Parse a date and time string and perform a conversion to UTC or local time. Parse(String, IFormatProvider, DateTimeStyles) 重载Parse(String, IFormatProvider, DateTimeStyles) overload
分析日期和时间字符串,而不处理异常。Parse a date and time string without handling exceptions. DateTime.TryParse 方法DateTime.TryParse method
还原(往返)由格式设置操作创建的日期和时间值。Restore (round-trip) a date and time value created by a formatting operation. ToString(String) 方法传递 "o" 或 "r" 标准格式字符串,并通过 @no__t 调用 @no__t 1 重载Pass the "o" or "r" standard format string to the ToString(String) method, and call the Parse(String, IFormatProvider, DateTimeStyles) overload with DateTimeStyles.RoundtripKind
跨计算机(和可能的文化)边界分析固定格式的日期和时间字符串。Parse a date and time string in a fixed format across machine (and possibly cultural) boundaries. DateTime.ParseExactDateTime.TryParseExact 方法DateTime.ParseExact or DateTime.TryParseExact method

要分析的字符串The string to parse

@No__t 0 方法尝试将日期和时间值的字符串表示形式转换为其等效的 @no__t。The Parse method tries to convert the string representation of a date and time value to its DateTime equivalent. 它会尝试完全分析输入字符串,而不会引发 FormatException 异常。It tries to parse the input string completely without throwing a FormatException exception.

重要

如果由于无法识别的字符串格式而导致分析操作失败,则 Parse 方法将引发 FormatException,而 @no__t 2 方法返回 falseIf the parsing operation fails because of an unrecognized string format, the Parse method throws a FormatException, whereas the TryParse method returns false. 由于异常处理可能会消耗大量资源,因此应在分析操作成功成功时使用 Parse,因为输入源受信任。Because exception handling can be expensive, you should use Parse when the parsing operation is expected to succeed because the input source is trusted. 当分析失败很可能时(特别是由于输入源不受信任),或者具有合理的默认值来替换不能成功分析的字符串时,TryParseTryParse is preferable when parsing failures are likely, particularly because an input source is not trusted, or you have reasonable default values to substitute for strings that do not parse successfully.

要分析的字符串可以采用以下任何形式:The string to be parsed can take any of the following forms:

  • 包含日期和时间组成部分的字符串。A string with a date and a time component.

  • 一个具有日期但没有时间部分的字符串。A string with a date but no time component. 如果时间部分不存在,则该方法假定为12:00 午夜。If the time component is absent, the method assumes 12:00 midnight. 如果日期部分的年份是两位数,则它将基于当前区域性当前日历的 @no__t 0 或指定区域性的当前日历(如果使用具有非 null @no__t 参数的重载)转换为年份。If the date component has a two-digit year, it is converted to a year based on the Calendar.TwoDigitYearMax of the current culture's current calendar or the specified culture's current calendar (if you use an overload with a non-null provider argument).

  • 包含日期部分的字符串,仅包含月份和年份,但不包括日期部分。A string with a date component that includes only the month and the year but no day component. 方法假设每月的第一天。The method assumes the first day of the month.

  • 包含日期部分的字符串,仅包含月份和日期,但不包括年份部分。A string with a date component that includes only the month and the day but no year component. 方法假定当前年份。The method assumes the current year.

  • 带有时间但没有日期部分的字符串。A string with a time but no date component. 此方法假定当前日期,除非调用 @no__t 0 重载,并在 styles 参数中包含 DateTimeStyles.NoCurrentDateDefault,在这种情况下,该方法假设日期为0001年1月1日。The method assumes the current date unless you call the Parse(String, IFormatProvider, DateTimeStyles) overload and include DateTimeStyles.NoCurrentDateDefault in the styles argument, in which case the method assumes a date of January 1, 0001.

  • 包含时间部分的字符串,其中仅包含小时和 AM/PM 指示符,不包含日期部分。A string with a time component that includes only the hour and an AM/PM designator, with no date component. 方法假定当前日期和时间无分钟且无秒。The method assumes the current date and a time with no minutes and no seconds. 您可以通过调用 @no__t 0 重载来更改此行为,并在 styles 参数中包含 DateTimeStyles.NoCurrentDateDefault,在这种情况下,该方法假设日期为0001年1月1日。You can change this behavior by calling the Parse(String, IFormatProvider, DateTimeStyles) overload and include DateTimeStyles.NoCurrentDateDefault in the styles argument, in which case the method assumes a date of January 1, 0001.

  • 包含时区信息并符合 ISO 8601 的字符串。A string that includes time zone information and conforms to ISO 8601. 在下面的示例中,第一个字符串指定协调世界时(UTC),第二个字符串指定时区中的时间早于 UTC 7 小时:In the following examples, the first string designates Coordinated Universal Time (UTC), and the second designates the time in a time zone that's seven hours earlier than UTC:

    "2008-11-01T19:35: 00.0000000 Z""2008-11-01T19:35:00.0000000Z"
    "01T19:35: 00.0000000-07: 00""2008-11-01T19:35:00.0000000-07:00"

  • 包含 GMT 指示符并符合 RFC 1123 时间格式的字符串;例如:A string that includes the GMT designator and conforms to the RFC 1123 time format; for example:

    "Sat,01 11 11 2008 19:35:00 GMT""Sat, 01 Nov 2008 19:35:00 GMT"

  • 一个字符串,其中包含日期和时间以及时区偏移量信息;例如:A string that includes the date and time along with time zone offset information; for example:

    "03/01/2009 05:42:00-5:00""03/01/2009 05:42:00 -5:00"

下面的示例使用当前区域性的格式设置约定(在本例中为 en-us 区域性)分析每种格式的字符串:The following example parses strings in each of these formats by using the formatting conventions of the current culture, which in this case is the en-US culture:

using System;

public class Example
{
   public static void Main()
   {
      (string dateAsString, string description)[]  dateInfo = { ("08/18/2018 07:22:16", "String with a date and time component"),                             
                                                                ("08/18/2018", "String with a date component only"),
                                                                ("8/2018", "String with a month and year component only"),
                                                                ("8/18", "String with a month and day component only"),
                                                                ("07:22:16", "String with a time component only"),
                                                                ("7 PM", "String with an hour and AM/PM designator only"),
                                                                ("2018-08-18T07:22:16.0000000Z", "UTC string that conforms to ISO 8601"),   
                                                                ("2018-08-18T07:22:16.0000000-07:00", "Non-UTC string that conforms to ISO 8601"),
                                                                ("Sat, 18 Aug 2018 07:22:16 GMT", "String that conforms to RFC 1123"),
                                                                ("08/18/2018 07:22:16 -5:00", "String with date, time, and time zone information" ) };
   
      Console.WriteLine($"Today is {DateTime.Now:d}\n");
      
      foreach (var item in dateInfo) {
         Console.WriteLine($"{item.description + ":",-52} '{item.dateAsString}' --> {DateTime.Parse(item.dateAsString)}");        
      }
   }
}
// The example displays output like the following:
//   Today is 2/22/2018
//   
//   String with a date and time component:               '08/18/2018 07:22:16' --> 8/18/2018 7:22:16 AM
//   String with a date component only:                   '08/18/2018' --> 8/18/2018 12:00:00 AM
//   String with a month and year component only:         '8/2018' --> 8/1/2018 12:00:00 AM
//   String with a month and day component only:          '8/18' --> 8/18/2018 12:00:00 AM
//   String with a time component only:                   '07:22:16' --> 2/22/2018 7:22:16 AM
//   String with an hour and AM/PM designator only:       '7 PM' --> 2/22/2018 7:00:00 PM
//   UTC string that conforms to ISO 8601:                '2018-08-18T07:22:16.0000000Z' --> 8/18/2018 12:22:16 AM
//   Non-UTC string that conforms to ISO 8601:            '2018-08-18T07:22:16.0000000-07:00' --> 8/18/2018 7:22:16 AM
//   String that conforms to RFC 1123:                    'Sat, 18 Aug 2018 07:22:16 GMT' --> 8/18/2018 12:22:16 AM
//   String with date, time, and time zone information:   '08/18/2018 07:22:16 -5:00' --> 8/18/2018 5:22:16 AM


Public Module Strings
   Public Sub Main()
      Dim dateInfo() As (dateAsString As String, description As String) = 
                     { ("08/18/2018 07:22:16", "String with a date and time component"),
                       ("08/18/2018", "String with a date component only"),
                       ("8/2018", "String with a month and year component only"),
                       ("8/18", "String with a month and day component only"),
                       ("07:22:16", "String with a time component only"),
                       ("7 PM", "String with an hour and AM/PM designator only"),
                       ("2018-08-18T07:22:16.0000000Z", "UTC string that conforms to ISO 8601"),   
                       ("2018-08-18T07:22:16.0000000-07:00", "Non-UTC string that conforms to ISO 8601"),
                       ("Sat, 18 Aug 2018 07:22:16 GMT", "String that conforms to RFC 1123"),
                       ("08/18/2018 07:22:16 -5:00", "String with date, time, and time zone information" ) }
   
      Console.WriteLine($"Today is {Date.Now:d}{vbCrLf}")
      
      For Each item in dateInfo
         Console.WriteLine($"{item.description + ":",-52} '{item.dateAsString}' --> {DateTime.Parse(item.dateAsString)}")        
      Next
   End Sub
End Module
' The example displays output like the following:
'   Today is 2/22/2018
'   
'   String with a date and time component:               '08/18/2018 07:22:16' --> 8/18/2018 7:22:16 AM
'   String with a date component only:                   '08/18/2018' --> 8/18/2018 12:00:00 AM
'   String with a month and year component only:         '8/2018' --> 8/1/2018 12:00:00 AM
'   String with a month and day component only:          '8/18' --> 8/18/2018 12:00:00 AM
'   String with a time component only:                   '07:22:16' --> 2/22/2018 7:22:16 AM
'   String with an hour and AM/PM designator only:       '7 PM' --> 2/22/2018 7:00:00 PM
'   UTC string that conforms to ISO 8601:                '2018-08-18T07:22:16.0000000Z' --> 8/18/2018 12:22:16 AM
'   Non-UTC string that conforms to ISO 8601:            '2018-08-18T07:22:16.0000000-07:00' --> 8/18/2018 7:22:16 AM
'   String that conforms to RFC 1123:                    'Sat, 18 Aug 2018 07:22:16 GMT' --> 8/18/2018 12:22:16 AM
'   String with date, time, and time zone information:   '08/18/2018 07:22:16 -5:00' --> 8/18/2018 5:22:16 AM

如果输入字符串表示在分析方法所使用的日历中的闰年的闰日(请参阅分析和区域性约定),则 Parse 方法会成功分析字符串。If the input string represents a leap day in a leap year in the calendar used by the parsing method (see Parsing and cultural conventions), the Parse method parses the string successfully. 如果输入字符串表示非闰年中的闰日,则该方法将引发 FormatExceptionIf the input string represents a leap day in a non-leap year, the method throws a FormatException.

由于 @no__t 0 方法尝试通过使用当前或指定区域性的格式设置规则来分析日期和时间的字符串表示形式,因此尝试跨不同区域性分析字符串会失败。Because the Parse method tries to parse the string representation of a date and time by using the formatting rules of the current or a specified culture, trying to parse a string across different cultures can fail. 若要在不同的区域设置中分析特定的日期和时间格式,请使用 DateTime.ParseExact 方法的重载之一,并提供格式说明符。To parse a specific date and time format across different locales, use one of the overloads of the DateTime.ParseExact method and provide a format specifier.

分析和文化约定Parsing and cultural conventions

除非要分析的字符串(由下表中的 s 表示)符合 ISO 8601 模式,否则 Parse 方法的所有重载都是区分区域性的。All overloads of the Parse method are culture-sensitive unless the string to be parsed (which is represented by s in the following table) conforms to the ISO 8601 pattern. 分析操作使用派生的 @no__t 0 对象中的格式设置信息,如下所示:The parsing operation uses the formatting information in a DateTimeFormatInfo object that is derived as follows:

重要

日本历法中的年号是根据天皇统治来命名的,因此预计会发生变化。Eras in the Japanese calendars are based on the emperor's reign and are therefore expected to change. 例如,2019 年 5 月 1 日在 JapaneseCalendarJapaneseLunisolarCalendar 中标志着令和年号的开始。For example, May 1, 2019 marked the beginning of the Reiwa era in the JapaneseCalendar and JapaneseLunisolarCalendar. 这种年号的变化会影响使用这些日历的所有应用程序。Such a change of era affects all applications that use these calendars. 请参阅 Handling a new era in the Japanese calendar in .NET(使用 .NET 处理日语日历中的新元号),了解详细信息并确定是否会影响你的应用程序。See Handling a new era in the Japanese calendar in .NET for more information and to determine whether your applications are affected. 请参阅针对日语元号更改准备应用程序,了解有关在 Windows 系统上测试应用程序以确保针对元号更改的准备情况信息。See Prepare your application for the Japanese era change for information on testing your applications on Windows systems to ensure their readiness for the era change. 有关 .Net 中支持多个年号日历的功能,以及在使用支持多个年号的日历时的最佳做法,请参阅使用年号See Working with eras for features in .NET that support calendars with multiple eras and for best practices when working with calendars that support multiple eras.

如果调用If you call 和 @no__t 为And provider is 格式设置信息派生自Formatting information is derived from
Parse(String) - 当前线程区域性(DateTimeFormatInfo.CurrentInfo 属性)The current thread culture (DateTimeFormatInfo.CurrentInfo property)
Parse(String, IFormatProvider)Parse(String, IFormatProvider, DateTimeStyles)Parse(String, IFormatProvider) or Parse(String, IFormatProvider, DateTimeStyles) 一个 @no__t 0 对象a DateTimeFormatInfo object 指定的 @no__t 0 对象The specified DateTimeFormatInfo object
Parse(String, IFormatProvider)Parse(String, IFormatProvider, DateTimeStyles)Parse(String, IFormatProvider) or Parse(String, IFormatProvider, DateTimeStyles) null 当前线程区域性(DateTimeFormatInfo.CurrentInfo 属性)The current thread culture (DateTimeFormatInfo.CurrentInfo property)
Parse(String, IFormatProvider)Parse(String, IFormatProvider, DateTimeStyles)Parse(String, IFormatProvider) or Parse(String, IFormatProvider, DateTimeStyles) 一个 @no__t 0 对象a CultureInfo object CultureInfo.DateTimeFormat 属性The CultureInfo.DateTimeFormat property
Parse(String, IFormatProvider)Parse(String, IFormatProvider, DateTimeStyles)Parse(String, IFormatProvider) or Parse(String, IFormatProvider, DateTimeStyles) 自定义 IFormatProvider 实现Custom IFormatProvider implementation IFormatProvider.GetFormat 方法The IFormatProvider.GetFormat method

当格式设置信息派生自 @no__t 0 对象时,@no__t 属性定义在分析操作中使用的日历。When formatting information is derived from a DateTimeFormatInfo object, the DateTimeFormatInfo.Calendar property defines the calendar used in the parsing operation.

如果 @no__t 使用与标准区域性不同的自定义设置来分析日期和时间字符串,则使用 ParseExact 方法,而不是 Parse 方法来提高成功转换的几率。If you parse a date and time string by using a DateTimeFormatInfo object with customized settings that are different from those of a standard culture, use the ParseExact method instead of the Parse method to improve the chances for a successful conversion. 非标准日期和时间字符串可能比较复杂且难以分析。A non-standard date and time string can be complicated and difficult to parse. @No__t-0 方法尝试使用几个隐式分析模式分析字符串,所有这些模式都可能失败。The Parse method tries to parse a string with several implicit parse patterns, all of which might fail. 与此相反,ParseExact 方法要求您显式指定一个或多个可能成功的完全分析模式。In contrast, the ParseExact method requires you to explicitly designate one or more exact parse patterns that are likely to succeed. 有关详细信息,请参阅 @no__t 主题中的 "DateTimeFormatInfo and 动态数据" 部分。For more information, see the "DateTimeFormatInfo and Dynamic Data" section in the DateTimeFormatInfo topic.

重要

请注意,特定区域性的格式设置约定是动态的,可能会发生更改。Note that the formatting conventions for a particular culture are dynamic and can be subject to change. 这意味着,如果发生以下任何情况,则依赖于默认(当前)区域性的格式设置约定的分析操作或指定一个 @no__t 0 对象(该对象表示除固定区域性以外的区域性)可能会意外失败:This means that parsing operations that depend on the formatting conventions of the default (current) culture or that specify an IFormatProvider object that represents a culture other than the invariant culture can unexpectedly fail if any of the following occurs:

  • 区域性特定的数据在 .NET Framework 的主版本或次版本中发生了更改,或作为 .NET Framework 的现有版本的更新结果。The culture-specific data has changed between major or minor versions of the .NET Framework or as the result of an update to the existing version of the .NET Framework.
  • 特定于区域性的数据反映用户首选项,这些首选项因计算机而异,或会话之间有所不同。The culture-specific data reflects user preferences, which can vary from machine to machine or session to session.
  • 特定于区域性的数据表示替代区域性,替代了标准区域性或自定义区域性的设置。The culture-specific data represents a replacement culture that overrides the settings of a standard culture or a custom culture.

若要避免在分析与区域性数据中的更改关联的数据和时间字符串时遇到困难,可以使用固定区域性来分析日期和时间字符串,也可以调用 @no__t 0 或 @no__t 方法并指定字符串的精确格式。要分析的。To prevent the difficulties in parsing data and time strings that are associated with changes in cultural data, you can parse date and time strings by using the invariant culture, or you can call the ParseExact or TryParseExact method and specify the exact format of the string to be parsed. 如果要序列化和反序列化日期和时间数据,则可以使用固定区域性的格式约定,也可以序列化和反序列化二进制格式的 @no__t 0 值。If you are serializing and deserializing date and time data, you can either use the formatting conventions of the invariant culture, or you can serialize and deserialize the DateTime value in a binary format.

有关详细信息,请参阅 @no__t 主题中的 CultureInfo 主题和 "保留日期时间值" 部分中的 "动态区域性数据" 部分。For more information see the "Dynamic culture data" section in the CultureInfo topic and the "Persisting DateTime values" section in the DateTime topic.

分析和样式元素Parsing and style elements

所有 Parse 重载都忽略输入字符串中的前导、内部或尾随空白字符(由下表中的 s 表示)。All Parse overloads ignore leading, inner, or trailing white-space characters in the input string (which is represented by s in the following table). 日期和时间可以用一对前导和尾随数字符号字符("#"、U + 0023)括起来,并且可以使用一个或多个 NULL 字符(U + 0000)进行 trailed。The date and time can be bracketed with a pair of leading and trailing NUMBER SIGN characters ("#", U+0023), and can be trailed with one or more NULL characters (U+0000).

此外,@no__t 0 重载具有一个 @no__t 参数,该参数包含一个或多个 @no__t 2 枚举的成员。In addition, the Parse(String, IFormatProvider, DateTimeStyles) overload has a styles parameter that consists of one or more members of the DateTimeStyles enumeration. 此参数定义应该如何解释 @no__t 0,以及分析操作应该如何将 s 转换为日期和时间。This parameter defines how s should be interpreted and how the parse operation should convert s to a date and time. 下表描述了每个 DateTimeStyles 成员对分析操作的影响。The following table describes the effect of each DateTimeStyles member on the parse operation.

DateTimeStyles 成员DateTimeStyles member 转换后的效果Effect on conversion
AdjustToUniversal 分析 s,并在必要时将其转换为 UTC,如下所示:Parses s and, if necessary, converts it to UTC, as follows:

-如果 s 包括时区偏移量,或者 s @no__t 不包含 AssumeLocal 标志,则该方法会分析该字符串,调用 ToUniversalTime 将返回的第5个值转换为 UTC,并将 Kind 属性设置为 @no__t。- If s includes a time zone offset, or if s contains no time zone information but styles includes the AssumeLocal flag, the method parses the string, calls ToUniversalTime to convert the returned DateTime value to UTC, and sets the Kind property to DateTimeKind.Utc.
-如果 s 指示它表示 UTC,或者 s 不包含时区信息,但 styles 包含 AssumeUniversal 标志,则方法将分析字符串,不对返回的 @no__t 值执行时区转换,并将 @no__t属性为 DateTimeKind.Utc- If s indicates that it represents UTC, or if s does not contain time zone information but styles includes the AssumeUniversal flag, the method parses the string, performs no time zone conversion on the returned DateTime value, and sets the Kind property to DateTimeKind.Utc.
-在所有其他情况下,该标志不起作用。- In all other cases, the flag has no effect.
AllowInnerWhite 忽略此值。This value is ignored. @No__t 的日期和时间元素中始终允许内部空格。Inner white space is always permitted in the date and time elements of s.
AllowLeadingWhite 忽略此值。This value is ignored. @No__t-0 的日期和时间元素中始终允许使用前导空格。Leading white space is always permitted in the date and time elements of s.
AllowTrailingWhite 忽略此值。This value is ignored. @No__t 的日期和时间元素中始终允许尾随空格。Trailing white space is always permitted in the date and time elements of s.
AllowWhiteSpaces 指定 s 可以包含前导空格和尾随空格。Specifies that s may contain leading, inner, and trailing white spaces. 这是默认行为。This is the default behavior. 不能通过提供限制性更强的 DateTimeStyles 枚举值(如 None)来重写它。It cannot be overridden by supplying a more restrictive DateTimeStyles enumeration value such as None.
AssumeLocal 指定如果 s 缺少任何时区信息,则假定为本地时间。Specifies that if s lacks any time zone information, local time is assumed. 除非存在 AdjustToUniversal 标志,否则返回的 DateTime 值的 @no__t 属性将设置为 DateTimeKind.LocalUnless the AdjustToUniversal flag is present, the Kind property of the returned DateTime value is set to DateTimeKind.Local.
AssumeUniversal 指定如果 s 缺少任何时区信息,则采用 UTC。Specifies that if s lacks any time zone information, UTC is assumed. 除非存在 AdjustToUniversal 标志,否则方法会将返回的 DateTime 值从 UTC 转换为本地时间,并将其 @no__t 2 属性设置为 DateTimeKind.LocalUnless the AdjustToUniversal flag is present, the method converts the returned DateTime value from UTC to local time and sets its Kind property to DateTimeKind.Local.
None 虽然有效,但会忽略此值。Although valid, this value is ignored.
RoundtripKind 对于包含时区信息的字符串,尝试防止将日期和时间字符串转换为表示本地时间的 @no__t 0 值,并将其 @no__t 属性设置为 DateTimeKind.LocalFor strings that contain time zone information, tries to prevent the conversion of a date and time string to a DateTime value that represents a local time with its Kind property set to DateTimeKind.Local. 通常,通过调用 DateTime.ToString(String) 方法并使用 "o"、"r" 或 "u" 标准格式说明符来创建此类字符串。Typically, such a string is created by calling the DateTime.ToString(String) method and by using the "o", "r", or "u" standard format specifier.

返回值和日期时间类型The return value and DateTime.Kind

@No__t-0 重载返回 Kind 属性包含时区信息的 @no__t 1 值。The DateTime.Parse overloads return a DateTime value whose Kind property includes time zone information. 它可以指示时间为:It can indicate that the time is:

通常情况下,Parse 方法返回 Kind 属性为 DateTimeKind.Unspecified 的 @no__t 1 对象。Generally, the Parse method returns a DateTime object whose Kind property is DateTimeKind.Unspecified. Parse 方法还可能执行时区转换,并以不同的方式设置 @no__t 属性的值,具体取决于 @no__t 和 @no__t 参数的值:However, the Parse method may also perform time zone conversion and set the value of the Kind property differently, depending on the values of the s and styles parameters:

如果If 时区转换Time zone conversion Kind 属性Kind property
s 包含时区信息。s contains time zone information. 日期和时间将转换为本地时区中的时间。The date and time is converted to the time in the local time zone. DateTimeKind.Local
@no__t 包含时区信息,styles 包含 @no__t 2 标志。s contains time zone information, and styles includes the AdjustToUniversal flag. 日期和时间转换为协调世界时(UTC)。The date and time is converted to Coordinated Universal Time (UTC). DateTimeKind.Utc
s 包含 Z 或 GMT 时区指示符,styles 包括 @no__t 2 标志。s contains the Z or GMT time zone designator, and styles includes the RoundtripKind flag. 日期和时间解释为 UTC。The date and time are interpreted as UTC. DateTimeKind.Utc

下面的示例将包含时区信息的日期字符串转换为本地时区中的时间:The following example converts date strings that contain time zone information to the time in the local time zone:

using System;

public class Example
{
   public static void Main()
   {
      string[] dateStrings = {"2008-05-01T07:34:42-5:00", 
                              "2008-05-01 7:34:42Z", 
                              "Thu, 01 May 2008 07:34:42 GMT"};
      foreach (string dateString in dateStrings)
      {
         DateTime convertedDate = DateTime.Parse(dateString);
         Console.WriteLine($"Converted {dateString} to {convertedDate.Kind} time {convertedDate}");
      }                              
   }
}
// These calls to the DateTime.Parse method display the following output:
//  Converted 2008-05-01T07:34:42-5:00 to Local time 5/1/2008 5:34:42 AM
//  Converted 2008-05-01 7:34:42Z to Local time 5/1/2008 12:34:42 AM
//  Converted Thu, 01 May 2008 07:34:42 GMT to Local time 5/1/2008 12:34:42 AM                                             
Module Example
   Public Sub Main()
      Dim dateStrings() As String = {"2008-05-01T07:34:42-5:00", 
                                     "2008-05-01 7:34:42Z", 
                                     "Thu, 01 May 2008 07:34:42 GMT"}
      
      For Each dateStr In dateStrings
         Dim convertedDate As Date = Date.Parse(dateStr)
         Console.WriteLine($"Converted {dateStr} to {convertedDate.Kind} time {convertedDate}")
      Next 
   End Sub
End Module
' These calls to the DateTime.Parse method display the following output:
'   Converted 2008-05-01T07:34:42-5:00 to Local time 5/1/2008 5:34:42 AM
'   Converted 2008-05-01 7:34:42Z to Local time 5/1/2008 12:34:42 AM
'   Converted Thu, 01 May 2008 07:34:42 GMT to Local time 5/1/2008 12:34:42 AM                                             

还可以通过使用 DateTimeStyles.RoundtripKind 标志在格式设置和分析操作期间保留日期和时间的 @no__t 的值。You can also preserve the value of a date and time's Kind property during a formatting and parsing operation by using the DateTimeStyles.RoundtripKind flag. 下面的示例说明了 RoundtripKind 标志如何影响通过使用 "o"、"r" 或 "u" 格式说明符转换为字符串的 @no__t 1 值的分析操作。The following example illustrates how the RoundtripKind flag affects the parsing operation on DateTime values that are converted to strings by using the "o", "r", or "u" format specifier.

   string[] formattedDates = { "2008-09-15T09:30:41.7752486-07:00", 
                               "2008-09-15T09:30:41.7752486Z",  
                               "2008-09-15T09:30:41.7752486",  
                               "2008-09-15T09:30:41.7752486-04:00", 
                               "Mon, 15 Sep 2008 09:30:41 GMT" };
   foreach (string formattedDate in formattedDates)
   {
      Console.WriteLine(formattedDate);
      DateTime roundtripDate = DateTime.Parse(formattedDate, null, 
                                              DateTimeStyles.RoundtripKind);                        
      Console.WriteLine($"   With RoundtripKind flag: {roundtripDate} {roundtripDate.Kind} time.");
   
      DateTime noRoundtripDate = DateTime.Parse(formattedDate, null, 
                                                DateTimeStyles.None);
      Console.WriteLine($"   Without RoundtripKind flag: {noRoundtripDate} {noRoundtripDate.Kind} time.");
   }         
// The example displays the following output:
//       2008-09-15T09:30:41.7752486-07:00
//          With RoundtripKind flag: 9/15/2008 9:30:41 AM Local time.
//          Without RoundtripKind flag: 9/15/2008 9:30:41 AM Local time.
//       2008-09-15T09:30:41.7752486Z
//          With RoundtripKind flag: 9/15/2008 9:30:41 AM Utc time.
//          Without RoundtripKind flag: 9/15/2008 2:30:41 AM Local time.
//       2008-09-15T09:30:41.7752486
//          With RoundtripKind flag: 9/15/2008 9:30:41 AM Unspecified time.
//          Without RoundtripKind flag: 9/15/2008 9:30:41 AM Unspecified time.
//       2008-09-15T09:30:41.7752486-04:00
//          With RoundtripKind flag: 9/15/2008 6:30:41 AM Local time.
//          Without RoundtripKind flag: 9/15/2008 6:30:41 AM Local time.
//       Mon, 15 Sep 2008 09:30:41 GMT
//          With RoundtripKind flag: 9/15/2008 9:30:41 AM Utc time.
//          Without RoundtripKind flag: 9/15/2008 2:30:41 AM Local time.      
Dim formattedDates() = { "2008-09-15T09:30:41.7752486-07:00", 
                           "2008-09-15T09:30:41.7752486Z",  
                           "2008-09-15T09:30:41.7752486",  
                           "2008-09-15T09:30:41.7752486-04:00", 
                           "Mon, 15 Sep 2008 09:30:41 GMT" }
For Each formattedDate In formattedDates
   Console.WriteLine(formattedDate)
   Dim roundtripDate = DateTime.Parse(formattedDate, Nothing,  
                                      DateTimeStyles.RoundtripKind)                        
   Console.WriteLine($"   With RoundtripKind flag: {roundtripDate} {roundtripDate.Kind} time.")                                          
   Dim noRoundtripDate = DateTime.Parse(formattedDate, Nothing,                                                                                                  DateTimeStyles.None)
   Console.WriteLine($"   Without RoundtripKind flag: {noRoundtripDate} {noRoundtripDate.Kind} time.")
Next         
' The example displays the following output:
'       2008-09-15T09:30:41.7752486-07:00
'          With RoundtripKind flag: 9/15/2008 9:30:41 AM Local time.
'          Without RoundtripKind flag: 9/15/2008 9:30:41 AM Local time.
'       2008-09-15T09:30:41.7752486Z
'          With RoundtripKind flag: 9/15/2008 9:30:41 AM Utc time.
'          Without RoundtripKind flag: 9/15/2008 2:30:41 AM Local time.
'       2008-09-15T09:30:41.7752486
'          With RoundtripKind flag: 9/15/2008 9:30:41 AM Unspecified time.
'          Without RoundtripKind flag: 9/15/2008 9:30:41 AM Unspecified time.
'       2008-09-15T09:30:41.7752486-04:00
'          With RoundtripKind flag: 9/15/2008 6:30:41 AM Local time.
'          Without RoundtripKind flag: 9/15/2008 6:30:41 AM Local time.
'       Mon, 15 Sep 2008 09:30:41 GMT
'          With RoundtripKind flag: 9/15/2008 9:30:41 AM Utc time.
'          Without RoundtripKind flag: 9/15/2008 2:30:41 AM Local time.      

Parse(String) Parse(String) Parse(String) Parse(String)

使用当前线程区域性的约定将日期和时间的字符串表示形式转换为其等效的 DateTimeConverts the string representation of a date and time to its DateTime equivalent by using the conventions of the current thread culture.

public:
 static DateTime Parse(System::String ^ s);
public static DateTime Parse (string s);
static member Parse : string -> DateTime
Public Shared Function Parse (s As String) As DateTime

参数

s
String String String String

包含要转换的日期和时间的字符串。A string that contains a date and time to convert. 有关详细信息,请参阅要分析的字符串See The string to parse for more information.

返回

一个对象,它等效于 s 中包含的日期和时间。An object that is equivalent to the date and time contained in s.

异常

s 不包含日期和时间的有效字符串表示形式。s does not contain a valid string representation of a date and time.

注解

如果 s 包含时区信息,则此方法将返回一个 @no__t 1 值,其 @no__t 2 属性为 DateTimeKind.Local,并将 @no__t 中的日期和时间转换为本地时间。If s contains time zone information, this method returns a DateTime value whose Kind property is DateTimeKind.Local and converts the date and time in s to local time. 否则,它不执行时区转换,并返回其 @no__t 属性为 DateTimeKind.Unspecified @no__t 0 值。Otherwise, it performs no time zone conversion and returns a DateTime value whose Kind property is DateTimeKind.Unspecified.

此重载尝试使用当前区域性的格式设置约定来分析 sThis overload attempts to parse s by using the formatting conventions of the current culture. 当前区域性由 CurrentCulture 属性指示。The current culture is indicated by the CurrentCulture property. 若要使用特定区域性的格式设置约定分析字符串,请调用 Parse(String, IFormatProvider)Parse(String, IFormatProvider, DateTimeStyles) 重载。To parse a string using the formatting conventions of a specific culture, call the Parse(String, IFormatProvider) or the Parse(String, IFormatProvider, DateTimeStyles) overloads.

此重载尝试使用 @no__t 样式分析 sThis overload attempts to parse s by using DateTimeStyles.AllowWhiteSpaces style.

示例Example

下面的示例通过以下方式分析几个日期和时间值的字符串表示形式:The following example parses the string representation of several date and time values by:

  • 使用默认格式提供程序,该提供程序提供用于生成示例输出的计算机的当前线程区域性的格式设置约定。Using the default format provider, which provides the formatting conventions of the current thread culture of the computer used to produce the example output. 此示例的输出反映了 en-us 区域性的格式设置约定。The output from this example reflects the formatting conventions of the en-US culture.

  • 使用默认样式值 AllowWhiteSpacesUsing the default style value, which is AllowWhiteSpaces.

它处理当方法尝试使用其他区域性的格式设置约定分析日期和时间的字符串表示形式时引发的 @no__t 0 异常。It handles the FormatException exception that is thrown when the method tries to parse the string representation of a date and time by using some other culture's formatting conventions. 它还演示如何成功分析不使用当前线程区域性的格式设置约定的日期和时间值。It also shows how to successfully parse a date and time value that does not use the formatting conventions of the current thread culture.

using System;
using System.Globalization;

public class DateTimeParser
{
   public static void Main()
   {
      // Assume the current culture is en-US. 
      // The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.

      // Use standard en-US date and time value
      DateTime dateValue;
      string dateString = "2/16/2008 12:15:12 PM";
      try {
         dateValue = DateTime.Parse(dateString);
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
      }   
      catch (FormatException) {
         Console.WriteLine("Unable to convert '{0}'.", dateString);
      }
            
      // Reverse month and day to conform to the fr-FR culture.
      // The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.
      dateString = "16/02/2008 12:15:12";
      try {
         dateValue = DateTime.Parse(dateString);
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
      }   
      catch (FormatException) {
         Console.WriteLine("Unable to convert '{0}'.", dateString);
      }

      // Call another overload of Parse to successfully convert string
      // formatted according to conventions of fr-FR culture.      
      try {
         dateValue = DateTime.Parse(dateString, new CultureInfo("fr-FR", false));
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
      }   
      catch (FormatException) {
         Console.WriteLine("Unable to convert '{0}'.", dateString);
      }
      
      // Parse string with date but no time component.
      dateString = "2/16/2008";
      try {
         dateValue = DateTime.Parse(dateString);
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
      }   
      catch (FormatException) {
         Console.WriteLine("Unable to convert '{0}'.", dateString);
      }   
   }
}
// The example displays the following output to the console:
//       '2/16/2008 12:15:12 PM' converted to 2/16/2008 12:15:12 PM.
//       Unable to convert '16/02/2008 12:15:12'.
//       '16/02/2008 12:15:12' converted to 2/16/2008 12:15:12 PM.
//       '2/16/2008' converted to 2/16/2008 12:00:00 AM.
Imports System.Globalization

Class DateTimeParser
   Public Shared Sub Main()
      ' Assume the current culture is en-US. 
      ' The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.

      ' Use standard en-US date and time value
      Dim dateValue As Date
      Dim dateString As String = "2/16/2008 12:15:12 PM"
      Try
         dateValue = Date.Parse(dateString)
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue)
      Catch e As FormatException
         Console.WriteLine("Unable to convert '{0}'.", dateString)
      End Try
            
      ' Reverse month and day to conform to the fr-FR culture.
      ' The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.
      dateString = "16/02/2008 12:15:12"
      Try
         dateValue = Date.Parse(dateString)
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue)
      Catch e As FormatException
         Console.WriteLine("Unable to convert '{0}'.", dateString)
      End Try

      ' Call another overload of Parse to successfully convert string
      ' formatted according to conventions of fr-FR culture.      
      Try
         dateValue = Date.Parse(dateString, New CultureInfo("fr-FR", False))
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue)
      Catch e As FormatException
         Console.WriteLine("Unable to convert '{0}'.", dateString)
      End Try
      
      ' Parse string with date but no time component.
      dateString = "2/16/2008"
      Try
         dateValue = Date.Parse(dateString)
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue)
      Catch e As FormatException
         Console.WriteLine("Unable to convert '{0}'.", dateString)
      End Try
   End Sub 
End Class 
' The example displays the following output to the console:
'       '2/16/2008 12:15:12 PM' converted to 2/16/2008 12:15:12 PM.
'       Unable to convert '16/02/2008 12:15:12'.
'       '16/02/2008 12:15:12' converted to 2/16/2008 12:15:12 PM.
'       '2/16/2008' converted to 2/16/2008 12:00:00 AM.
另请参阅

Parse(String, IFormatProvider) Parse(String, IFormatProvider) Parse(String, IFormatProvider) Parse(String, IFormatProvider)

使用指定的区域性特定格式设置信息,将日期和时间的字符串表示形式转换为其等效的 DateTimeConverts the string representation of a date and time to its DateTime equivalent by using culture-specific format information.

public:
 static DateTime Parse(System::String ^ s, IFormatProvider ^ provider);
public static DateTime Parse (string s, IFormatProvider provider);
static member Parse : string * IFormatProvider -> DateTime
Public Shared Function Parse (s As String, provider As IFormatProvider) As DateTime

参数

s
String String String String

包含要转换的日期和时间的字符串。A string that contains a date and time to convert. 有关详细信息,请参阅要分析的字符串See The string to parse for more information.

provider
IFormatProvider IFormatProvider IFormatProvider IFormatProvider

一个对象,提供有关 s 的区域性特定格式信息。An object that supplies culture-specific format information about s. 请参阅分析和区域性约定See Parsing and cultural conventions

返回

一个对象,它等效于 s 中包含的日期和时间,由 provider 指定。An object that is equivalent to the date and time contained in s as specified by provider.

异常

s 不包含日期和时间的有效字符串表示形式。s does not contain a valid string representation of a date and time.

注解

如果 s 包含时区信息,则此方法将返回一个 @no__t 1 值,其 @no__t 2 属性为 DateTimeKind.Local,并将 @no__t 中的日期和时间转换为本地时间。If s contains time zone information, this method returns a DateTime value whose Kind property is DateTimeKind.Local and converts the date and time in s to local time. 否则,它不执行时区转换,并返回其 @no__t 属性为 DateTimeKind.Unspecified @no__t 0 值。Otherwise, it performs no time zone conversion and returns a DateTime value whose Kind property is DateTimeKind.Unspecified.

此重载尝试使用 @no__t 样式分析 sThis overload attempts to parse s by using the DateTimeStyles.AllowWhiteSpaces style.

示例Example

下面的示例使用 en-us、fr 和 de 消除文化的约定分析日期字符串的数组。The following example parses an array of date strings by using the conventions of the en-US, fr-FR, and de-DE cultures. 它演示单个日期的字符串表示形式可以在不同的区域性中以不同的方式解释。It demonstrates that the string representations of a single date can be interpreted differently across different cultures.

using System;
using System.Globalization;

public class ParseDate
{
   public static void Main()
   {
      // Define cultures to be used to parse dates.
      CultureInfo[] cultures = {CultureInfo.CreateSpecificCulture("en-US"), 
                                CultureInfo.CreateSpecificCulture("fr-FR"), 
                                CultureInfo.CreateSpecificCulture("de-DE")};
      // Define string representations of a date to be parsed.
      string[] dateStrings = {"01/10/2009 7:34 PM", 
                              "10.01.2009 19:34", 
                              "10-1-2009 19:34" };
      // Parse dates using each culture.
      foreach (CultureInfo culture in cultures)
      {
         DateTime dateValue;
         Console.WriteLine("Attempted conversions using {0} culture.", 
                           culture.Name);
         foreach (string dateString in dateStrings)
         {
            try {
               dateValue = DateTime.Parse(dateString, culture);
               Console.WriteLine("   Converted '{0}' to {1}.",
                                 dateString, dateValue.ToString("f", culture));
            }
            catch (FormatException) {
               Console.WriteLine("   Unable to convert '{0}' for culture {1}.", 
                                 dateString, culture.Name);
            }
         }
         Console.WriteLine();
      }                                                                                     
   }
}
// The example displays the following output to the console:
//       Attempted conversions using en-US culture.
//          Converted '01/10/2009 7:34 PM' to Saturday, January 10, 2009 7:34 PM.
//          Converted '10.01.2009 19:34' to Thursday, October 01, 2009 7:34 PM.
//          Converted '10-1-2009 19:34' to Thursday, October 01, 2009 7:34 PM.
//       
//       Attempted conversions using fr-FR culture.
//          Converted '01/10/2009 7:34 PM' to jeudi 1 octobre 2009 19:34.
//          Converted '10.01.2009 19:34' to samedi 10 janvier 2009 19:34.
//          Converted '10-1-2009 19:34' to samedi 10 janvier 2009 19:34.
//       
//       Attempted conversions using de-DE culture.
//          Converted '01/10/2009 7:34 PM' to Donnerstag, 1. Oktober 2009 19:34.
//          Converted '10.01.2009 19:34' to Samstag, 10. Januar 2009 19:34.
//          Converted '10-1-2009 19:34' to Samstag, 10. Januar 2009 19:34.
Imports System.Globalization

Module ParseDate
   Public Sub Main()
      ' Define cultures to be used to parse dates.
      Dim cultures() As CultureInfo = {CultureInfo.CreateSpecificCulture("en-US"), _
                                       CultureInfo.CreateSpecificCulture("fr-FR"), _
                                       CultureInfo.CreateSpecificCulture("de-DE")}
      ' Define string representations of a date to be parsed.
      Dim dateStrings() As String = {"01/10/2009 7:34 PM", _
                                     "10.01.2009 19:34", _
                                     "10-1-2009 19:34" }
      ' Parse dates using each culture.
      For Each culture In cultures
         Dim dateValue As Date
         Console.WriteLine("Attempted conversions using {0} culture.", culture.Name)
         For Each dateString As String In dateStrings
            Try
               dateValue = Date.Parse(dateString, culture)
               Console.WriteLine("   Converted '{0}' to {1}.", _
                                 dateString, dateValue.ToString("f", culture))
            Catch e As FormatException
               Console.WriteLine("   Unable to convert '{0}' for culture {1}.", _
                                 dateString, culture.Name)
            End Try                                                
         Next
         Console.WriteLine()
      Next                                                                                     
   End Sub
End Module
' The example displays the following output to the console:
'       Attempted conversions using en-US culture.
'          Converted '01/10/2009 7:34 PM' to Saturday, January 10, 2009 7:34 PM.
'          Converted '10.01.2009 19:34' to Thursday, October 01, 2009 7:34 PM.
'          Converted '10-1-2009 19:34' to Thursday, October 01, 2009 7:34 PM.
'       
'       Attempted conversions using fr-FR culture.
'          Converted '01/10/2009 7:34 PM' to jeudi 1 octobre 2009 19:34.
'          Converted '10.01.2009 19:34' to samedi 10 janvier 2009 19:34.
'          Converted '10-1-2009 19:34' to samedi 10 janvier 2009 19:34.
'       
'       Attempted conversions using de-DE culture.
'          Converted '01/10/2009 7:34 PM' to Donnerstag, 1. Oktober 2009 19:34.
'          Converted '10.01.2009 19:34' to Samstag, 10. Januar 2009 19:34.
'          Converted '10-1-2009 19:34' to Samstag, 10. Januar 2009 19:34.
另请参阅

Parse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles) Parse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles) Parse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles)

使用指定的区域性特定格式设置信息和格式类型,将包含日期和时间的字符串表示形式的内存范围转换为其等效的 DateTimeConverts a memory span that contains string representation of a date and time to its DateTime equivalent by using culture-specific format information and a formatting style.

public static DateTime Parse (ReadOnlySpan<char> s, IFormatProvider provider = null, System.Globalization.DateTimeStyles styles = System.Globalization.DateTimeStyles.None);
static member Parse : ReadOnlySpan<char> * IFormatProvider * System.Globalization.DateTimeStyles -> DateTime
Public Shared Function Parse (s As ReadOnlySpan(Of Char), Optional provider As IFormatProvider = null, Optional styles As DateTimeStyles = System.Globalization.DateTimeStyles.None) As DateTime

参数

s
ReadOnlySpan<Char>

包含要分析的字符串的内存范围。The memory span that contains the string to parse. 有关详细信息,请参阅要分析的字符串See The string to parse for more information.

provider
IFormatProvider IFormatProvider IFormatProvider IFormatProvider

一个对象,提供有关 s 的区域性特定格式信息。An object that supplies culture-specific format information about s. 请参阅分析和区域性约定See Parsing and cultural conventions

styles
DateTimeStyles DateTimeStyles DateTimeStyles DateTimeStyles

枚举值的按位组合,用于指示 s 成功执行分析操作所需的样式元素以及定义如何根据当前时区或当前日期解释已分析日期的样式元素。A bitwise combination of the enumeration values that indicates the style elements that can be present in s for the parse operation to succeed, and that defines how to interpret the parsed date in relation to the current time zone or the current date. 要指定的一个典型值为 NoneA typical value to specify is None.

返回

一个对象,它等效于 s 中包含的日期和时间,由 providerstyles 指定。An object that is equivalent to the date and time contained in s, as specified by provider and styles.

异常

s 不包含日期和时间的有效字符串表示形式。s does not contain a valid string representation of a date and time.

styles 包含无效的 DateTimeStyles 值组合。styles contains an invalid combination of DateTimeStyles values. 例如,AssumeLocalAssumeUniversalFor example, both AssumeLocal and AssumeUniversal.

Parse(String, IFormatProvider, DateTimeStyles) Parse(String, IFormatProvider, DateTimeStyles) Parse(String, IFormatProvider, DateTimeStyles) Parse(String, IFormatProvider, DateTimeStyles)

使用指定的区域性特定格式设置信息和格式类型,将日期和时间的字符串表示形式转换为其等效的 DateTimeConverts the string representation of a date and time to its DateTime equivalent by using culture-specific format information and a formatting style.

public:
 static DateTime Parse(System::String ^ s, IFormatProvider ^ provider, System::Globalization::DateTimeStyles styles);
public static DateTime Parse (string s, IFormatProvider provider, System.Globalization.DateTimeStyles styles);
static member Parse : string * IFormatProvider * System.Globalization.DateTimeStyles -> DateTime
Public Shared Function Parse (s As String, provider As IFormatProvider, styles As DateTimeStyles) As DateTime

参数

s
String String String String

包含要转换的日期和时间的字符串。A string that contains a date and time to convert. 有关详细信息,请参阅要分析的字符串See The string to parse for more information.

provider
IFormatProvider IFormatProvider IFormatProvider IFormatProvider

一个对象,提供有关 s 的区域性特定格式设置信息。An object that supplies culture-specific formatting information about s. 请参阅分析和区域性约定See Parsing and cultural conventions

styles
DateTimeStyles DateTimeStyles DateTimeStyles DateTimeStyles

枚举值的按位组合,用于指示 s 成功执行分析操作所需的样式元素以及定义如何根据当前时区或当前日期解释已分析日期的样式元素。A bitwise combination of the enumeration values that indicates the style elements that can be present in s for the parse operation to succeed, and that defines how to interpret the parsed date in relation to the current time zone or the current date. 要指定的一个典型值为 NoneA typical value to specify is None.

返回

一个对象,它等效于 s 中包含的日期和时间,由 providerstyles 指定。An object that is equivalent to the date and time contained in s, as specified by provider and styles.

异常

s 不包含日期和时间的有效字符串表示形式。s does not contain a valid string representation of a date and time.

styles 包含无效的 DateTimeStyles 值组合。styles contains an invalid combination of DateTimeStyles values. 例如,AssumeLocalAssumeUniversalFor example, both AssumeLocal and AssumeUniversal.

注解

此方法重载将日期和时间转换为 s 并设置返回的 DateTime 值的 @no__t 属性,如下所示:This method overload converts the date and time in s and sets the Kind property of the returned DateTime value as follows:

如果If 时区转换Time zone conversion Kind 属性Kind property
s 不包含时区信息。s contains no time zone information. 无。None. DateTimeKind.Unspecified
s 包含时区信息。s contains time zone information. 到本地时区的时间To the time in the local time zone DateTimeKind.Local
@no__t 包含时区信息,styles 包含 @no__t 2 标志。s contains time zone information, and styles includes the DateTimeStyles.AdjustToUniversal flag. 到协调世界时(UTC)To Coordinated Universal Time (UTC) DateTimeKind.Utc
s 包含 Z 或 GMT 时区指示符,styles 包含 DateTimeStyles.RoundtripKinds contains the Z or GMT time zone designator, and styles includes the DateTimeStyles.RoundtripKind. 无。None. DateTimeKind.Utc

示例Example

下面的示例演示 Parse(String, IFormatProvider, DateTimeStyles) 方法,并显示生成的 DateTime 值的 @no__t 属性的值。The following example demonstrates the Parse(String, IFormatProvider, DateTimeStyles) method and displays the value of the Kind property of the resulting DateTime values.

using System;
using System.Globalization;

public class ParseDateExample
{
   public static void Main()
   {
      string dateString;
      CultureInfo culture ;
      DateTimeStyles styles;
      DateTime result;
      
      // Parse a date and time with no styles.
      dateString = "03/01/2009 10:00 AM";
      culture = CultureInfo.CreateSpecificCulture("en-US");
      styles = DateTimeStyles.None;
      try {
         result = DateTime.Parse(dateString, culture, styles);
         Console.WriteLine("{0} converted to {1} {2}.", 
                           dateString, result, result.Kind.ToString());
      }
      catch (FormatException) {
         Console.WriteLine("Unable to convert {0} to a date and time.", 
                           dateString);
      }      
      
      // Parse the same date and time with the AssumeLocal style.
      styles = DateTimeStyles.AssumeLocal;
      try {
         result = DateTime.Parse(dateString, culture, styles);
         Console.WriteLine("{0} converted to {1} {2}.", 
                           dateString, result, result.Kind.ToString());
      }
      catch (FormatException) {
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString);
      }      
      
      // Parse a date and time that is assumed to be local.
      // This time is five hours behind UTC. The local system's time zone is 
      // eight hours behind UTC.
      dateString = "2009/03/01T10:00:00-5:00";
      styles = DateTimeStyles.AssumeLocal;
      try {
         result = DateTime.Parse(dateString, culture, styles);
         Console.WriteLine("{0} converted to {1} {2}.", 
                           dateString, result, result.Kind.ToString());
      }
      catch (FormatException) {
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString);
      }      
      
      // Attempt to convert a string in improper ISO 8601 format.
      dateString = "03/01/2009T10:00:00-5:00";
      try {
         result = DateTime.Parse(dateString, culture, styles);
         Console.WriteLine("{0} converted to {1} {2}.", 
                           dateString, result, result.Kind.ToString());
      }                     
      catch (FormatException) {
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString);
      }      

      // Assume a date and time string formatted for the fr-FR culture is the local 
      // time and convert it to UTC.
      dateString = "2008-03-01 10:00";
      culture = CultureInfo.CreateSpecificCulture("fr-FR");
      styles = DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeLocal;
      try {
         result = DateTime.Parse(dateString, culture, styles);
         Console.WriteLine("{0} converted to {1} {2}.", 
                           dateString, result, result.Kind.ToString());
      }
      catch (FormatException) {
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString);
      }      
   }
}
// The example displays the following output to the console:
//       03/01/2009 10:00 AM converted to 3/1/2009 10:00:00 AM Unspecified.
//       03/01/2009 10:00 AM converted to 3/1/2009 10:00:00 AM Local.
//       2009/03/01T10:00:00-5:00 converted to 3/1/2009 7:00:00 AM Local.
//       Unable to convert 03/01/2009T10:00:00-5:00 to a date and time.
//       2008-03-01 10:00 converted to 3/1/2008 6:00:00 PM Utc.
Imports System.Globalization

Module ParseDateExample
   Public Sub Main()
      Dim dateString As String  
      Dim culture As CultureInfo
      Dim styles As DateTimeStyles 
      Dim result As DateTime
      
      ' Parse a date and time with no styles.
      dateString = "03/01/2009 10:00 AM"
      culture = CultureInfo.CreateSpecificCulture("en-US")
      styles = DateTimeStyles.None
      Try
         result = DateTime.Parse(dateString, culture, styles)
         Console.WriteLine("{0} converted to {1} {2}.", _
                           dateString, result, result.Kind.ToString())
      Catch e As FormatException
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString)
      End Try      
      
      ' Parse the same date and time with the AssumeLocal style.
      styles = DateTimeStyles.AssumeLocal
      Try
         result = DateTime.Parse(dateString, culture, styles)
         Console.WriteLine("{0} converted to {1} {2}.", _
                           dateString, result, result.Kind.ToString())
      Catch e As FormatException
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString)
      End Try      
      
      ' Parse a date and time that is assumed to be local.
      ' This time is five hours behind UTC. The local system's time zone is 
      ' eight hours behind UTC.
      dateString = "2009/03/01T10:00:00-5:00"
      styles = DateTimeStyles.AssumeLocal
      Try
         result = DateTime.Parse(dateString, culture, styles)
         Console.WriteLine("{0} converted to {1} {2}.", _
                           dateString, result, result.Kind.ToString())
      Catch e As FormatException
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString)
      End Try      
      
      ' Attempt to convert a string in improper ISO 8601 format.
      dateString = "03/01/2009T10:00:00-5:00"
      Try
         result = DateTime.Parse(dateString, culture, styles)
         Console.WriteLine("{0} converted to {1} {2}.", _
                           dateString, result, result.Kind.ToString())
      Catch e As FormatException
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString)
      End Try      

      ' Assume a date and time string formatted for the fr-FR culture is the local 
      ' time and convert it to UTC.
      dateString = "2008-03-01 10:00"
      culture = CultureInfo.CreateSpecificCulture("fr-FR")
      styles = DateTimeStyles.AdjustToUniversal Or DateTimeStyles.AssumeLocal
      Try
         result = DateTime.Parse(dateString, culture, styles)
         Console.WriteLine("{0} converted to {1} {2}.", _
                           dateString, result, result.Kind.ToString())
      Catch e As FormatException
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString)
      End Try      
   End Sub
End Module
'
' The example displays the following output to the console:
'       03/01/2009 10:00 AM converted to 3/1/2009 10:00:00 AM Unspecified.
'       03/01/2009 10:00 AM converted to 3/1/2009 10:00:00 AM Local.
'       2009/03/01T10:00:00-5:00 converted to 3/1/2009 7:00:00 AM Local.
'       Unable to convert 03/01/2009T10:00:00-5:00 to a date and time.
'       2008-03-01 10:00 converted to 3/1/2008 6:00:00 PM Utc.
另请参阅

适用于