DateTime.Parse 方法

定义

将日期和时间的字符串表示形式转换为其等效的 DateTime

重载

Parse(String)

使用当前区域性的约定将日期和时间的字符串表示形式转换为其 DateTime 等效的表示形式。

Parse(ReadOnlySpan<Char>, IFormatProvider)

将字符范围分析为值。

Parse(String, IFormatProvider)

使用指定的区域性特定格式设置信息,将日期和时间的字符串表示形式转换为其等效的 DateTime

Parse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles)

使用指定的区域性特定格式设置信息和格式类型,将包含日期和时间的字符串表示形式的内存范围转换为其等效的 DateTime

Parse(String, IFormatProvider, DateTimeStyles)

使用指定的区域性特定格式设置信息和格式类型,将日期和时间的字符串表示形式转换为其等效的 DateTime

示例

本文的“备注”部分和各个DateTime.Parse重载的文档中都穿插了大量调用 DateTime.Parse 方法的示例。

注意

本文中的一些 C# 示例运行在 Try.NET 内联代码运行程序和演练环境中。 选择“运行”按钮以在交互窗口中运行示例。 执行代码后,可通过再次选择“运行”来修改它并运行已修改的代码。 已修改的代码要么在交互窗口中运行,要么编译失败时,交互窗口将显示所有 C# 编译器错误消息。

Try.NET 内联代码运行程序和演练环境的本地时区是协调世界时 (UTC)。 这可能会影响用于说明 DateTimeDateTimeOffsetTimeZoneInfo 类型及其成员的示例的行为和输出。

还可以下载一组 DateTime.Parse 完整的示例,这些示例包含在 适用于 C# 的 .NET Core 项目中

注解

本节内容:

我调用哪种方法?

功能 调用
使用当前区域性的约定分析日期和时间字符串。 Parse(String) 重载
使用特定区域性的约定分析日期和时间字符串。 Parse(String, IFormatProvider) 重载 (请参阅 分析和区域性约定)
分析具有特殊样式元素的日期和时间字符串, (如空格或无空格) 。 Parse(String, IFormatProvider, DateTimeStyles) 重载
分析必须采用特定格式的日期和时间字符串。 DateTime.ParseExactDateTime.TryParseExact
分析日期和时间字符串,并执行到 UTC 或本地时间的转换。 Parse(String, IFormatProvider, DateTimeStyles) 重载
在不处理异常的情况下分析日期和时间字符串。 DateTime.TryParse 方法
还原 (往返) 格式设置操作创建的日期和时间值。 将“o”或“r”标准格式字符串传递给 ToString(String) 方法,并使用 调用 Parse(String, IFormatProvider, DateTimeStyles) 重载 DateTimeStyles.RoundtripKind
跨计算机 (可能具有区域性) 边界,以固定格式分析日期和时间字符串。 DateTime.ParseExactDateTime.TryParseExact 方法

要分析的字符串

方法 Parse 尝试将日期和时间值的字符串表示形式转换为其 DateTime 等效值。 它尝试完全分析输入字符串,而不会引发 FormatException 异常。

重要

如果分析操作由于无法识别的字符串格式而失败,该方法 ParseFormatException引发 ,而 TryParse 该方法返回 false。 由于异常处理成本可能很高,因此应在分析操作成功时使用 Parse ,因为输入源受信任。 TryParse 当分析失败可能时,更可取,特别是因为输入源不受信任,或者你有合理的默认值来替换未成功分析的字符串。

要分析的字符串可以采用以下任何形式:

  • 具有日期和时间部分的字符串。

  • 具有日期但没有时间组件的字符串。 如果时间部分不存在,该方法假定午夜 12:00。 如果日期组件有一个两位数的年份,则会根据 Calendar.TwoDigitYearMax 当前区域性的当前日历或指定区域性的当前日历 (使用具有非 null provider 参数的重载) 转换为年份。

  • 包含日期部分的字符串,该组件仅包含月份和年份,但不包含日期部分。 方法假定为当月的第一天。

  • 包含日期组件的字符串,该组件仅包含月和日,但不包含年份部分。 方法假定为当前年份。

  • 具有时间但没有日期组件的字符串。 方法假定当前日期,除非调用 Parse(String, IFormatProvider, DateTimeStyles) 重载并包含在 DateTimeStyles.NoCurrentDateDefaultstyles 参数中,在这种情况下,该方法假定日期为 0001 年 1 月 1 日。

  • 一个字符串,其时间组件仅包括小时和 AM/PM 指示符,不包含日期部分。 方法假定当前日期和时间没有分钟和秒。 可以通过调用 Parse(String, IFormatProvider, DateTimeStyles) 重载并包含在 DateTimeStyles.NoCurrentDateDefault 参数中 styles 来更改此行为,在这种情况下, 方法假定日期为 0001 年 1 月 1 日。

  • 包含时区信息并符合 ISO 8601 的字符串。 在以下示例中,第一个字符串指定协调世界时 (UTC) ,第二个字符串指定早于 UTC 7 小时的时区的时间:

    “2008-11-01T19:35:00.0000000Z”“2008-11-01T19:35:00.0000000-07:00”

  • 包含 GMT 指示符并符合 RFC 1123 时间格式的字符串;例如:

    “2008 年 11 月 1 日,星期六 19:35:00 GMT”

  • 包含日期和时间以及时区偏移信息的字符串;例如:

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

以下示例使用当前区域性的格式设置约定(在本例中为 en-US 区域性)分析每种格式的字符串:

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
module Parse6

open System

let  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" ]

printfn $"Today is {DateTime.Now:d}\n"

for dateAsString, description in dateInfo do
    printfn $"""{description + ":",-52} '{dateAsString}' --> {DateTime.Parse(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 该方法成功分析字符串。 如果输入字符串表示非闰年中的闰日,该方法将 FormatException引发 。

Parse由于 方法尝试使用当前或指定区域性的格式规则分析日期和时间的字符串表示形式,因此尝试跨不同区域性分析字符串可能会失败。 若要跨不同的区域设置分析特定的日期和时间格式,请使用 方法的 DateTime.ParseExact 重载之一并提供格式说明符。

分析和区域性约定

方法的所有重载 Parse 都区分区域性,除非要分析的字符串 (下表中表示 s) 符合 ISO 8601 模式。 分析操作使用派生的 对象中的 DateTimeFormatInfo 格式设置信息,如下所示:

重要

日本历法中的年号是根据天皇统治来命名的,因此预计会发生变化。 例如,2019 年 5 月 1 日在 JapaneseCalendarJapaneseLunisolarCalendar 中标志着令和年号的开始。 这种年号的变化会影响使用这些日历的所有应用程序。 有关详细信息并确定应用程序是否受到影响,请参阅 在 .NET 中处理日语日历中的新纪元。 有关在 Windows 系统上测试应用程序以确保其准备好进行纪元更改的信息,请参阅 准备应用程序应对日本纪元更改。 有关 .NET 中支持具有多个纪元的日历的功能以及使用支持多个纪元的日历时的最佳做法,请参阅 使用纪元

如果你调用 provider 格式设置信息派生自
Parse(String) - 当前区域性 (DateTimeFormatInfo.CurrentInfo 属性)
Parse(String, IFormatProvider)Parse(String, IFormatProvider, DateTimeStyles) DateTimeFormatInfo 对象 指定的 DateTimeFormatInfo 对象
Parse(String, IFormatProvider)Parse(String, IFormatProvider, DateTimeStyles) null 当前区域性 (DateTimeFormatInfo.CurrentInfo 属性)
Parse(String, IFormatProvider)Parse(String, IFormatProvider, DateTimeStyles) CultureInfo 对象 CultureInfo.DateTimeFormat 属性
Parse(String, IFormatProvider)Parse(String, IFormatProvider, DateTimeStyles) 自定义 IFormatProvider 实现 IFormatProvider.GetFormat 方法

当格式设置信息派生自 DateTimeFormatInfo 对象时, DateTimeFormatInfo.Calendar 属性定义分析操作中使用的日历。

如果使用具有不同于标准区域性设置的自定义设置的对象来分析日期和时间字符串 DateTimeFormatInfo ,请使用 ParseExact 方法而不是 Parse 方法来提高成功转换的机会。 非标准日期和时间字符串可能很复杂且难以分析。 方法 Parse 尝试分析具有多个隐式分析模式的字符串,所有这些模式都可能失败。 相反, ParseExact 方法要求显式指定一个或多个可能成功的精确分析模式。 有关详细信息,请参阅主题中的“DateTimeFormatInfo 和动态数据”部分 DateTimeFormatInfo

重要

请注意,特定区域性的格式设置约定是动态的,可能会发生更改。 这意味着,如果发生以下任一 IFormatProvider 情况,则分析依赖于默认 (当前) 区域性的格式设置约定或指定表示非固定区域性的对象的操作可能会意外失败:

  • 区域性特定的数据在.NET Framework的主要版本或次要版本之间或由于更新.NET Framework的现有版本而发生更改。
  • 区域性特定的数据反映了用户首选项,这些首选项可能因计算机或会话而异。
  • 区域性特定数据表示替代区域性,该区域性替代标准区域性或自定义区域性的设置。

为了防止在分析与区域性数据更改相关的数据和时间字符串时遇到困难,可以使用固定区域性来分析日期和时间字符串,也可以调用 ParseExactTryParseExact 方法并指定要分析的字符串的确切格式。 如果要序列化和反序列化日期和时间数据,则可以使用固定区域性的格式设置约定,也可以以二进制格式序列化和反序列化 DateTime 值。

有关详细信息,请参阅主题中的“动态区域性数据”部分 CultureInfo 和主题中的“持久保存 DateTime 值”部分 DateTime

分析和设置元素样式

所有重载都 Parse 忽略输入字符串 (s 中的前导、内部或尾随空格字符) 。 日期和时间可以用一对前导和尾随的 NUMBER SIGN 字符 (“#”、U+0023) 括起来,并且可以在 U+0000) (一个或多个 NULL 字符的尾随。

此外, Parse(String, IFormatProvider, DateTimeStyles) 重载具有一个 styles 参数,该参数由枚举的 DateTimeStyles 一个或多个成员组成。 此参数定义应如何 s 解释,以及分析操作应如何转换为 s 日期和时间。 下表描述了每个 DateTimeStyles 成员对分析操作的影响。

DateTimeStyles 成员 对转换的影响
AdjustToUniversal 分析 s 并在必要时将其转换为 UTC,如下所示:

- 如果 s 包含时区偏移量,或者如果 s 不包含时区信息但 styles 包含 AssumeLocal 标志,该方法将分析字符串,调用 ToUniversalTime 以将返回 DateTime 的值转换为 UTC,并将 属性 Kind 设置为 DateTimeKind.Utc
- 如果 s 指示它表示 UTC,或者如果 s 不包含时区信息但 styles 包含 AssumeUniversal 标志,则 方法将分析字符串,对返回 DateTime 的值不执行时区转换,并将 属性设置为 KindDateTimeKind.Utc
- 在所有其他情况下,标志不起作用。
AllowInnerWhite 忽略此值。 始终允许在 的日期和时间元素 s中使用内部空格。
AllowLeadingWhite 忽略此值。 始终允许在 的日期和时间元素 s中使用前导空格。
AllowTrailingWhite 忽略此值。 始终允许在 的日期和时间元素 s中使用尾随空格。
AllowWhiteSpaces 指定 s 可能包含前导空格、内部空格和尾随空格。 这是默认行为。 不能通过提供限制性更高的 DateTimeStyles 枚举值(例如 None)来重写它。
AssumeLocal 指定如果 s 缺少任何时区信息,则假定为本地时间。 AdjustToUniversal除非存在 标志,Kind否则返回DateTime值的 属性设置为 DateTimeKind.Local
AssumeUniversal 指定如果 s 缺少任何时区信息,则假定 UTC。 AdjustToUniversal除非标志存在,否则 方法会将返回DateTime的值从 UTC 转换为本地时间,并将其属性设置为 KindDateTimeKind.Local
None 虽然有效,但忽略此值。
RoundtripKind 对于包含时区信息的字符串,尝试阻止日期和时间字符串转换为 DateTime 表示本地时间的值,其 Kind 属性设置为 DateTimeKind.Local。 通常,通过调用 DateTime.ToString(String) 方法并使用“o”、“r”或“u”标准格式说明符来创建此类字符串。

返回值和 DateTime.Kind

DateTime.Parse 载返回一个 DateTime 值,其 Kind 属性包含时区信息。 它可以指示时间为:

通常, Parse 方法返回其DateTime属性为 DateTimeKind.Unspecified的对象Kind。 但是,Parse方法还可以执行时区转换,并设置 属性的值Kind,具体取决于 和 styles 参数的值s

如果 时区转换 Kind 属性
s 包含时区信息。 日期和时间将转换为本地时区中的时间。 DateTimeKind.Local
s 包含时区信息,并 styles 包含 AdjustToUniversal 标志。 日期和时间将转换为协调世界时 (UTC) 。 DateTimeKind.Utc
s 包含 Z 或 GMT 时区指示符,并 styles 包含 RoundtripKind 标志。 日期和时间解释为 UTC。 DateTimeKind.Utc

以下示例将包含时区信息的日期字符串转换为本地时区中的时间:

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
open System

let dateStrings = 
    [ "2008-05-01T07:34:42-5:00"
      "2008-05-01 7:34:42Z"
      "Thu, 01 May 2008 07:34:42 GMT" ]

for dateString in dateStrings do
    let convertedDate = DateTime.Parse dateString
    printfn $"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 标志保留日期和时间Kind属性的值。 以下示例演示标志如何影响 RoundtripKind 使用“o”、“r”或“u”格式说明符转换为字符串的值上的分析操作 DateTime

   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.
let 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 formattedDate in formattedDates do
    printfn $"{formattedDate}"
    let roundtripDate = DateTime.Parse(formattedDate, null, DateTimeStyles.RoundtripKind)
    printfn $"   With RoundtripKind flag: {roundtripDate} {roundtripDate.Kind} time."

    let noRoundtripDate = DateTime.Parse(formattedDate, null, DateTimeStyles.None)
    printfn $"   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)

Source:
DateTime.cs
Source:
DateTime.cs
Source:
DateTime.cs

使用当前区域性的约定将日期和时间的字符串表示形式转换为其 DateTime 等效的表示形式。

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

包含要转换的日期和时间的字符串。 有关详细信息,请参阅要分析的字符串

返回

一个对象,它等效于 s 中包含的日期和时间。

例外

snull

s 不包含日期和时间的有效字符串表示形式。

示例

以下示例通过以下方式分析多个日期和时间值的字符串表示形式:

  • 使用默认格式提供程序,该提供程序提供用于生成示例输出的计算机当前区域性的格式设置约定。 此示例的输出反映了 en-US 区域性的格式设置约定。

  • 使用默认样式值,即 AllowWhiteSpaces

它处理当 FormatException 方法尝试使用某些其他区域性的格式设置约定分析日期和时间的字符串表示形式时引发的异常。 它还演示如何成功分析不使用当前区域性的格式设置约定的日期和时间值。

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.
open System
open System.Globalization

[<EntryPoint>]
let 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
    let dateString = "2/16/2008 12:15:12 PM"
    try
        let dateValue = DateTime.Parse dateString
        printfn $"'{dateString}' converted to {dateValue}."
    with :? FormatException ->
        printfn $"Unable to convert '{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.
    let dateString = "16/02/2008 12:15:12"
    try
        let dateValue = DateTime.Parse dateString
        printfn $"'{dateString}' converted to {dateValue}."
    with :? 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
        let dateValue = DateTime.Parse(dateString, CultureInfo("fr-FR", false))
        printfn $"'{dateString}' converted to {dateValue}."
    with :? FormatException ->
        printfn $"Unable to convert '{dateString}'."

    // Parse string with date but no time component.
    let dateString = "2/16/2008"
    try
        let dateValue = DateTime.Parse dateString
        printfn $"'{dateString}' converted to {dateValue}."
    with :? FormatException ->
        printfn $"Unable to convert '{dateString}'."

    0

// 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.

注解

如果s包含时区信息,则此方法返回其 DateTime 属性为 DateTimeKind.Local 的值Kind,并将 中的s日期和时间转换为本地时间。 否则,它不执行时区转换,并返回其 DateTime 属性为 DateTimeKind.Unspecified的值Kind

此重载尝试使用当前区域性的格式设置约定进行分析 s 。 当前区域性由 CurrentCulture 属性指示。 若要使用特定区域性的格式设置约定分析字符串,请调用 Parse(String, IFormatProvider)Parse(String, IFormatProvider, DateTimeStyles) 重载。

此重载尝试使用 DateTimeStyles.AllowWhiteSpaces style 进行分析s

另请参阅

适用于

Parse(ReadOnlySpan<Char>, IFormatProvider)

Source:
DateTime.cs
Source:
DateTime.cs
Source:
DateTime.cs

将字符范围分析为值。

public:
 static DateTime Parse(ReadOnlySpan<char> s, IFormatProvider ^ provider) = ISpanParsable<DateTime>::Parse;
public static DateTime Parse (ReadOnlySpan<char> s, IFormatProvider? provider);
static member Parse : ReadOnlySpan<char> * IFormatProvider -> DateTime
Public Shared Function Parse (s As ReadOnlySpan(Of Char), provider As IFormatProvider) As DateTime

参数

s
ReadOnlySpan<Char>

要分析的字符范围。

provider
IFormatProvider

一个对象,提供有关 s 的区域性特定格式设置信息。

返回

分析 s的结果。

实现

适用于

Parse(String, IFormatProvider)

Source:
DateTime.cs
Source:
DateTime.cs
Source:
DateTime.cs

使用指定的区域性特定格式设置信息,将日期和时间的字符串表示形式转换为其等效的 DateTime

public:
 static DateTime Parse(System::String ^ s, IFormatProvider ^ provider);
public:
 static DateTime Parse(System::String ^ s, IFormatProvider ^ provider) = IParsable<DateTime>::Parse;
public static DateTime Parse (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

包含要转换的日期和时间的字符串。 有关详细信息,请参阅要分析的字符串

provider
IFormatProvider

一个对象,提供有关 s 的区域性特定格式信息。 请参阅分析和区域性约定

返回

一个对象,它等效于 s 中包含的日期和时间,由 provider 指定。

实现

例外

snull

s 不包含日期和时间的有效字符串表示形式。

示例

以下示例使用 en-US、fr-FR 和 de-DE 区域性的约定分析日期字符串数组。 它演示了单个日期的字符串表示形式可以跨不同的区域性以不同的方式解释。

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.
open System
open System.Globalization

// Define cultures to be used to parse dates.
let cultures = 
    [ CultureInfo.CreateSpecificCulture "en-US"
      CultureInfo.CreateSpecificCulture "fr-FR"
      CultureInfo.CreateSpecificCulture "de-DE" ]

// Define string representations of a date to be parsed.
let dateStrings = 
    [ "01/10/2009 7:34 PM"
      "10.01.2009 19:34"
      "10-1-2009 19:34" ]

// Parse dates using each culture.
for culture in cultures do
    printfn $"Attempted conversions using {culture.Name} culture."
    for dateString in dateStrings do
        try
            let dateValue = DateTime.Parse(dateString, culture)
            printfn $"""   Converted '{dateString}' to {dateValue.ToString("f", culture)}."""
        with :? FormatException ->
            printfn $"   Unable to convert '{dateString}' for culture {culture.Name}." 
    printfn ""


// 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.

注解

如果s包含时区信息,则此方法返回其 DateTime 属性为 DateTimeKind.Local 的值Kind,并将 中的s日期和时间转换为本地时间。 否则,它不执行时区转换,并返回其 DateTime 属性为 DateTimeKind.Unspecified的值Kind

此重载尝试使用 DateTimeStyles.AllowWhiteSpaces 样式进行分析s

另请参阅

适用于

Parse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles)

Source:
DateTime.cs
Source:
DateTime.cs
Source:
DateTime.cs

使用指定的区域性特定格式设置信息和格式类型,将包含日期和时间的字符串表示形式的内存范围转换为其等效的 DateTime

public static DateTime Parse (ReadOnlySpan<char> s, IFormatProvider? provider = default, System.Globalization.DateTimeStyles styles = System.Globalization.DateTimeStyles.None);
public static DateTime Parse (ReadOnlySpan<char> s, IFormatProvider provider = default, 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 = Nothing, Optional styles As DateTimeStyles = System.Globalization.DateTimeStyles.None) As DateTime

参数

s
ReadOnlySpan<Char>

包含要分析的字符串的内存范围。 有关详细信息,请参阅要分析的字符串

provider
IFormatProvider

一个对象,提供有关 s 的区域性特定格式信息。 请参阅分析和区域性约定

styles
DateTimeStyles

枚举值的按位组合,用于指示 s 成功执行分析操作所需的样式元素以及定义如何根据当前时区或当前日期解释已分析日期的样式元素。 要指定的一个典型值为 None

返回

一个对象,它等效于 s 中包含的日期和时间,由 providerstyles 指定。

例外

s 不包含日期和时间的有效字符串表示形式。

styles 包含无效的 DateTimeStyles 值组合。 例如,AssumeLocalAssumeUniversal

适用于

Parse(String, IFormatProvider, DateTimeStyles)

Source:
DateTime.cs
Source:
DateTime.cs
Source:
DateTime.cs

使用指定的区域性特定格式设置信息和格式类型,将日期和时间的字符串表示形式转换为其等效的 DateTime

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);
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

包含要转换的日期和时间的字符串。 有关详细信息,请参阅要分析的字符串

provider
IFormatProvider

一个对象,提供有关 s 的区域性特定格式设置信息。 请参阅分析和区域性约定

styles
DateTimeStyles

枚举值的按位组合,用于指示 s 成功执行分析操作所需的样式元素以及定义如何根据当前时区或当前日期解释已分析日期的样式元素。 要指定的一个典型值为 None

返回

一个对象,它等效于 s 中包含的日期和时间,由 providerstyles 指定。

例外

snull

s 不包含日期和时间的有效字符串表示形式。

styles 包含无效的 DateTimeStyles 值组合。 例如,AssumeLocalAssumeUniversal

示例

下面的示例演示 Parse(String, IFormatProvider, DateTimeStyles) 了 方法,并显示 Kind 结果 DateTime 值的 属性的值。

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.
open System
open System.Globalization

[<EntryPoint>]
let main _ =
    // Parse a date and time with no styles.
    let dateString = "03/01/2009 10:00 AM"
    let culture = CultureInfo.CreateSpecificCulture "en-US"
    let styles = DateTimeStyles.None
    try
        let result = DateTime.Parse(dateString, culture, styles)
        printfn $"{dateString} converted to {result} {result.Kind}."
    with :? FormatException ->
        printfn $"Unable to convert {dateString} to a date and time."

    // Parse the same date and time with the AssumeLocal style.
    let styles = DateTimeStyles.AssumeLocal
    try
        let result = DateTime.Parse(dateString, culture, styles)
        printfn $"{dateString} converted to {result} {result.Kind}."
    with :? FormatException ->
        printfn $"Unable to convert {dateString} to a date and time."

    // 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.
    let dateString = "2009/03/01T10:00:00-5:00"
    let styles = DateTimeStyles.AssumeLocal
    try
        let result = DateTime.Parse(dateString, culture, styles)
        printfn $"{dateString} converted to {result} {result.Kind}."
    with :? FormatException ->
        printfn $"Unable to convert {dateString} to a date and time."

    // Attempt to convert a string in improper ISO 8601 format.
    let dateString = "03/01/2009T10:00:00-5:00"
    try
        let result = DateTime.Parse(dateString, culture, styles)
        printfn $"{dateString} converted to {result} {result.Kind}."
    with :? FormatException ->
        printfn $"Unable to convert {dateString} to a date and time."

    // Assume a date and time string formatted for the fr-FR culture is the local
    // time and convert it to UTC.
    let dateString = "2008-03-01 10:00"
    let culture = CultureInfo.CreateSpecificCulture "fr-FR"
    let styles = DateTimeStyles.AdjustToUniversal ||| DateTimeStyles.AssumeLocal
    try
        let result = DateTime.Parse(dateString, culture, styles)
        printfn $"{dateString} converted to {result} {result.Kind}."
    with :? FormatException ->
        printfn $"Unable to convert {dateString} to a date and time."

    0

// 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.

注解

此方法重载在 中 s 转换日期和时间,并设置 Kind 返回 DateTime 值的 属性,如下所示:

如果 时区转换 Kind 属性
s 不包含时区信息。 无。 DateTimeKind.Unspecified
s 包含时区信息。 到本地时区的时间 DateTimeKind.Local
s 包含时区信息,并 styles 包含 DateTimeStyles.AdjustToUniversal 标志。 协调世界时 (UTC) DateTimeKind.Utc
s 包含 Z 或 GMT 时区指示符,并 styles 包含 DateTimeStyles.RoundtripKind 无。 DateTimeKind.Utc

另请参阅

适用于