System.Convert.ToDateTime 方法 (String, IFormatProvider)

方法描述

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

语法定义(C# System.Convert.ToDateTime 方法 (String, IFormatProvider) 的用法)

public static DateTime ToDateTime(
	string value,
	IFormatProvider provider
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
value System-String 包含要转换的日期和时间的字符串。
provider System-IFormatProvider 一个提供区域性特定的格式设置信息的对象。
返回值 System.DateTime value 的值的日期和时间等效项,如果 value 为 null,则为 DateTime.MinValue 的日期和时间等效项。

提示和注释

返回值是对 value 调用 DateTime.Parse(String, IFormatProvider) 方法的结果。

provider 是获取 DateTimeFormatInfo 对象的 IFormatProvider 实例。 DateTimeFormatInfo 对象提供有关 value 格式的区域性特定信息。 如果 provider 为 null,则使用当前区域性的 DateTimeFormatInfo。

如果您希望在转换失败时不处理异常,则可以转而调用 DateTime.TryParse 方法。 它将返回 Boolean 值,该值指示转换是否成功。

System.Convert.ToDateTime 方法 (String, IFormatProvider)例子

下面的代码示例使用 ToDateTime 方法,通过一个 IFormatProvider 对象转换日期值的字符串表示形式。

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      Console.WriteLine("{0,-18}{1,-12}{2}\n", "Date String", "Culture", "Result");

      string[] cultureNames = { "en-US", "ru-RU","ja-JP" };
      string[] dateStrings = { "01/02/09", "2009/02/03",  "01/2009/03", 
                               "01/02/2009", "21/02/09", "01/22/09",  
                               "01/02/23" };
      // Iterate each culture name in the array.
      foreach (string cultureName in cultureNames)
      {
         CultureInfo culture = new CultureInfo(cultureName);

         // Parse each date using the designated culture.
         foreach (string dateStr in dateStrings)
         {
            DateTime dateTimeValue;
            try {
               dateTimeValue = Convert.ToDateTime(dateStr, culture);
                // Display the date and time in a fixed format.
                Console.WriteLine("{0,-18}{1,-12}{2:yyyy-MMM-dd}",
                                  dateStr, cultureName, dateTimeValue);
            }
            catch (FormatException e) { 
                Console.WriteLine("{0,-18}{1,-12}{2}", 
                                  dateStr, cultureName, e.GetType().Name);
            }
         }
         Console.WriteLine();
      }
   }
}

异常

异常 异常描述
FormatException value 不是格式正确的日期和时间字符串。

命名空间

namespace: System

程序集: mscorlib(在 mscorlib.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0、1.1、1.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1 受以下版本支持:

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。