Convert.ToDateTime Convert.ToDateTime Convert.ToDateTime Convert.ToDateTime Method

定義

將指定的值轉換為 DateTime 值。Converts a specified value to a DateTime value.

多載

ToDateTime(Single) ToDateTime(Single) ToDateTime(Single) ToDateTime(Single)

呼叫這個方法一律會擲回 InvalidCastExceptionCalling this method always throws InvalidCastException.

ToDateTime(String) ToDateTime(String) ToDateTime(String) ToDateTime(String)

將指定之日期和時間的字串表示,轉換為相等的日期和時間值。Converts the specified string representation of a date and time to an equivalent date and time value.

ToDateTime(UInt16) ToDateTime(UInt16) ToDateTime(UInt16) ToDateTime(UInt16)

呼叫這個方法一律會擲回 InvalidCastExceptionCalling this method always throws InvalidCastException.

ToDateTime(String, IFormatProvider) ToDateTime(String, IFormatProvider) ToDateTime(String, IFormatProvider) ToDateTime(String, IFormatProvider)

使用指定之特定文化特性格式資訊,將指定之數字的字串表示轉換為相等的日期和時間。Converts the specified string representation of a number to an equivalent date and time, using the specified culture-specific formatting information.

ToDateTime(UInt64) ToDateTime(UInt64) ToDateTime(UInt64) ToDateTime(UInt64)

呼叫這個方法一律會擲回 InvalidCastExceptionCalling this method always throws InvalidCastException.

ToDateTime(Object, IFormatProvider) ToDateTime(Object, IFormatProvider) ToDateTime(Object, IFormatProvider) ToDateTime(Object, IFormatProvider)

使用指定之特定文化特性格式資訊,將指定之物件的值轉換為 DateTime 物件。Converts the value of the specified object to a DateTime object, using the specified culture-specific formatting information.

ToDateTime(SByte) ToDateTime(SByte) ToDateTime(SByte) ToDateTime(SByte)

呼叫這個方法一律會擲回 InvalidCastExceptionCalling this method always throws InvalidCastException.

ToDateTime(UInt32) ToDateTime(UInt32) ToDateTime(UInt32) ToDateTime(UInt32)

呼叫這個方法一律會擲回 InvalidCastExceptionCalling this method always throws InvalidCastException.

ToDateTime(Object) ToDateTime(Object) ToDateTime(Object) ToDateTime(Object)

將指定之物件的值轉換為 DateTime 物件。Converts the value of the specified object to a DateTime object.

ToDateTime(Double) ToDateTime(Double) ToDateTime(Double) ToDateTime(Double)

呼叫這個方法一律會擲回 InvalidCastExceptionCalling this method always throws InvalidCastException.

ToDateTime(Int32) ToDateTime(Int32) ToDateTime(Int32) ToDateTime(Int32)

呼叫這個方法一律會擲回 InvalidCastExceptionCalling this method always throws InvalidCastException.

ToDateTime(Boolean) ToDateTime(Boolean) ToDateTime(Boolean) ToDateTime(Boolean)

呼叫這個方法一律會擲回 InvalidCastExceptionCalling this method always throws InvalidCastException.

ToDateTime(Byte) ToDateTime(Byte) ToDateTime(Byte) ToDateTime(Byte)

呼叫這個方法一律會擲回 InvalidCastExceptionCalling this method always throws InvalidCastException.

ToDateTime(Char) ToDateTime(Char) ToDateTime(Char) ToDateTime(Char)

呼叫這個方法一律會擲回 InvalidCastExceptionCalling this method always throws InvalidCastException.

ToDateTime(Int64) ToDateTime(Int64) ToDateTime(Int64) ToDateTime(Int64)

呼叫這個方法一律會擲回 InvalidCastExceptionCalling this method always throws InvalidCastException.

ToDateTime(Decimal) ToDateTime(Decimal) ToDateTime(Decimal) ToDateTime(Decimal)

呼叫這個方法一律會擲回 InvalidCastExceptionCalling this method always throws InvalidCastException.

ToDateTime(Int16) ToDateTime(Int16) ToDateTime(Int16) ToDateTime(Int16)

呼叫這個方法一律會擲回 InvalidCastExceptionCalling this method always throws InvalidCastException.

ToDateTime(DateTime) ToDateTime(DateTime) ToDateTime(DateTime) ToDateTime(DateTime)

傳回指定的 DateTime 物件;不會執行實際的轉換。Returns the specified DateTime object; no actual conversion is performed.

ToDateTime(Single) ToDateTime(Single) ToDateTime(Single) ToDateTime(Single)

呼叫這個方法一律會擲回 InvalidCastExceptionCalling this method always throws InvalidCastException.

public:
 static DateTime ToDateTime(float value);
public static DateTime ToDateTime (float value);
static member ToDateTime : single -> DateTime
Public Shared Function ToDateTime (value As Single) As DateTime

參數

value
Single Single Single Single

要轉換的單精確度浮點數值。The single-precision floating-point value to convert.

傳回

不支援這個轉換。This conversion is not supported. 沒有傳回值。No value is returned.

例外狀況

不支援這個轉換。This conversion is not supported.

另請參閱

ToDateTime(String) ToDateTime(String) ToDateTime(String) ToDateTime(String)

將指定之日期和時間的字串表示,轉換為相等的日期和時間值。Converts the specified string representation of a date and time to an equivalent date and time value.

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

參數

value
String String String String

日期和時間的字串表示。The string representation of a date and time.

傳回

value 值相等的日期和時間;如果 MinValuevalue,則為與 null 相等的日期和時間。The date and time equivalent of the value of value, or the date and time equivalent of MinValue if value is null.

例外狀況

value 不是格式正確的日期和時間字串。value is not a properly formatted date and time string.

範例

下列範例會使用ToDateTime方法,將轉換的日期和時間,以各種不同的字串表示法DateTime值。The following example uses the ToDateTime method to convert various string representations of dates and times to DateTime values.

using System;

public class ConversionToDateTime
{
   public static void Main()
   {
      string dateString = null;
      
      // Convert a null string.
      ConvertToDateTime(dateString);
      
      // Convert an empty string.
      dateString = String.Empty;
      ConvertToDateTime(dateString);
      
      // Convert a non-date string.
      dateString = "not a date";
      ConvertToDateTime(dateString);
      
      // Try to convert various date strings.
      dateString = "05/01/1996";
      ConvertToDateTime(dateString);
      dateString = "Tue Apr 28, 2009";
      ConvertToDateTime(dateString);
      dateString = "Wed Apr 28, 2009";
      ConvertToDateTime(dateString);
      dateString = "06 July 2008 7:32:47 AM";
      ConvertToDateTime(dateString);
      dateString = "17:32:47.003";
      ConvertToDateTime(dateString);
      // Convert a string returned by DateTime.ToString("R").
      dateString = "Sat, 10 May 2008 14:32:17 GMT";
      ConvertToDateTime(dateString);
      // Convert a string returned by DateTime.ToString("o").
      dateString = "2009-05-01T07:54:59.9843750-04:00";
      ConvertToDateTime(dateString);
   }

   private static void ConvertToDateTime(string value)
   {
      DateTime convertedDate;
      try {
         convertedDate = Convert.ToDateTime(value);
         Console.WriteLine("'{0}' converts to {1} {2} time.", 
                           value, convertedDate, 
                           convertedDate.Kind.ToString());
      }
      catch (FormatException) {
         Console.WriteLine("'{0}' is not in the proper format.", value);
      }
   }
}
// The example displays the following output:
//    '' converts to 1/1/0001 12:00:00 AM Unspecified time.
//    '' is not in the proper format.
//    'not a date' is not in the proper format.
//    '05/01/1996' converts to 5/1/1996 12:00:00 AM Unspecified time.
//    'Tue Apr 28, 2009' converts to 4/28/2009 12:00:00 AM Unspecified time.
//    'Wed Apr 28, 2009' is not in the proper format.
//    '06 July 2008 7:32:47 AM' converts to 7/6/2008 7:32:47 AM Unspecified time.
//    '17:32:47.003' converts to 5/30/2008 5:32:47 PM Unspecified time.
//    'Sat, 10 May 2008 14:32:17 GMT' converts to 5/10/2008 7:32:17 AM Local time.
//    '2009-05-01T07:54:59.9843750-04:00' converts to 5/1/2009 4:54:59 AM Local time.
Module ConversionToDateTime
   Public Sub Main()
      Dim dateString As String = Nothing
      
      ' Convert a null string.
      ConvertToDateTime(dateString)
      
      ' Convert an empty string.
      dateString = String.Empty
      ConvertToDateTime(dateString)
      
      ' Convert a non-date string.
      dateString = "not a date"
      ConvertToDateTime(dateString)
      
      ' Try to convert various date strings.
      dateString = "05/01/1996"
      ConvertToDateTime(dateString)
      dateString = "Tue Apr 28, 2009"
      ConvertToDateTime(dateString)
      dateString = "Wed Apr 28, 2009"
      ConvertToDateTime(dateString)
      dateString = "06 July 2008 7:32:47 AM"
      ConvertToDateTime(dateString)
      dateString = "17:32:47.003"
      ConvertToDateTime(dateString)
      ' Convert a string returned by DateTime.ToString("R").
      dateString = "Sat, 10 May 2008 14:32:17 GMT"
      ConvertToDateTime(dateString)
      ' Convert a string returned by DateTime.ToString("o")
      dateString = "2009-05-01T07:54:59.9843750-04:00"
      ConvertToDateTime(dateString)
   End Sub
   
   Private Sub ConvertToDateTime(value As String)
      Dim convertedDate As Date
      Try
         convertedDate = Convert.ToDateTime(value)
         Console.WriteLine("'{0}' converts to {1}.", value, convertedDate)
      Catch e As FormatException
         Console.WriteLine("'{0}' is not in the proper format.", value)
      End Try
   End Sub
End Module
' The example displays the following output:
'    '' converts to 1/1/0001 12:00:00 AM.
'    '' is not in the proper format.
'    'not a date' is not in the proper format.
'    '05/01/1996' converts to 5/1/1996 12:00:00 AM.
'    'Tue Apr 28, 2009' converts to 4/28/2009 12:00:00 AM.
'    'Wed Apr 28, 2009' is not in the proper format.
'    '06 July 2008 7:32:47 AM' converts to 7/6/2008 7:32:47 AM.
'    '17:32:47.003' converts to 5/30/2008 5:32:47 PM.
'    'Sat, 10 May 2008 14:32:17 GMT' converts to 5/10/2008 7:32:17 AM.
'    '2009-05-01T07:54:59.9843750-04:00' converts to 5/1/2009 4:54:59 AM.

備註

如果value不是null,則傳回值是叫用的結果DateTime.Parse方法value使用中的格式設定資訊DateTimeFormatInfo初始化目前的文化特性的物件。If value is not null, the return value is the result of invoking the DateTime.Parse method on value using the formatting information in a DateTimeFormatInfo object that is initialized for the current culture. value引數必須包含日期的表示法,並說明其中一種格式的時間DateTimeFormatInfo主題。The value argument must contain the representation of a date and time in one of the formats described in the DateTimeFormatInfo topic. 如果 valuenull,則方法會傳回 DateTime.MinValueIf value is null, the method returns DateTime.MinValue.

這個方法會嘗試剖析value完全並避免擲回FormatExceptionThis method tries to parse value completely and avoid throwing a FormatException. 完成遺漏月、 日和年資訊使用目前的日期。It completes missing month, day, and year information with the current date. 如果value包含只有日期而沒有時間中,這個方法會假設午夜的時間。If value contains only a date and no time, this method assumes a time of midnight. 前置、 內部或尾端空格字元,在value都會被忽略。Any leading, inner, or trailing white-space characters in value are ignored.

如果您不想處理的例外狀況,如果轉換失敗,您可以呼叫DateTime.TryParse方法改為。If you prefer not to handle an exception if the conversion fails, you can call the DateTime.TryParse method instead. 它會傳回Boolean值,指出轉換是否成功或失敗。It returns a Boolean value that indicates whether the conversion succeeded or failed.

另請參閱

ToDateTime(UInt16) ToDateTime(UInt16) ToDateTime(UInt16) ToDateTime(UInt16)

重要

此 API 不符合 CLS 規範。

呼叫這個方法一律會擲回 InvalidCastExceptionCalling this method always throws InvalidCastException.

public:
 static DateTime ToDateTime(System::UInt16 value);
[System.CLSCompliant(false)]
public static DateTime ToDateTime (ushort value);
static member ToDateTime : uint16 -> DateTime
Public Shared Function ToDateTime (value As UShort) As DateTime

參數

value
UInt16 UInt16 UInt16 UInt16

要轉換之 16 位元不帶正負號的整數。The 16-bit unsigned integer to convert.

傳回

不支援這個轉換。This conversion is not supported. 沒有傳回值。No value is returned.

例外狀況

不支援這個轉換。This conversion is not supported.

另請參閱

ToDateTime(String, IFormatProvider) ToDateTime(String, IFormatProvider) ToDateTime(String, IFormatProvider) ToDateTime(String, IFormatProvider)

使用指定之特定文化特性格式資訊,將指定之數字的字串表示轉換為相等的日期和時間。Converts the specified string representation of a number to an equivalent date and time, using the specified culture-specific formatting information.

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

參數

value
String String String String

字串,包含要轉換的日期和時間。A string that contains a date and time to convert.

provider
IFormatProvider IFormatProvider IFormatProvider IFormatProvider

物件,提供特定文化特性格式資訊。An object that supplies culture-specific formatting information.

傳回

value 值相等的日期和時間;如果 MinValuevalue,則為與 null 相等的日期和時間。The date and time equivalent of the value of value, or the date and time equivalent of MinValue if value is null.

例外狀況

value 不是格式正確的日期和時間字串。value is not a properly formatted date and time string.

範例

下列範例會將日期值的字串表示法ToDateTime方法,使用IFormatProvider物件。The following example converts string representations of date values with the ToDateTime method, using an IFormatProvider object.

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();
      }
   }
}
Imports System.Globalization

Module Example
   Public Sub Main( )
      Console.WriteLine("{0,-18}{1,-12}{2}", "Date String", "Culture", "Result")
      Console.WriteLine()

      Dim cultureNames() As String = { "en-US", "ru-RU","ja-JP" }
      Dim dateStrings() As String = { "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.
      For Each cultureName As String In cultureNames
         Dim culture As CultureInfo = New CultureInfo(cultureName)
        
         ' Parse each date using the designated culture.
         For Each dateStr As String In dateStrings
            Dim dateTimeValue As DateTime
            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 e As FormatException 
                Console.WriteLine("{0,-18}{1,-12}{2}", _
                                  dateStr, cultureName, e.GetType().Name)
            End Try            
         Next
         Console.WriteLine()
      Next
   End Sub 
End Module 
' The example displays the following output:
'       Date String       Culture     Result
'       
'       01/02/09          en-US       2009-Jan-02
'       2009/02/03        en-US       2009-Feb-03
'       01/2009/03        en-US       2009-Jan-03
'       01/02/2009        en-US       2009-Jan-02
'       21/02/09          en-US       FormatException
'       01/22/09          en-US       2009-Jan-22
'       01/02/23          en-US       2023-Jan-02
'       
'       01/02/09          ru-RU       2009-Feb-01
'       2009/02/03        ru-RU       2009-Feb-03
'       01/2009/03        ru-RU       2009-Jan-03
'       01/02/2009        ru-RU       2009-Feb-01
'       21/02/09          ru-RU       2009-Feb-21
'       01/22/09          ru-RU       FormatException
'       01/02/23          ru-RU       2023-Feb-01
'       
'       01/02/09          ja-JP       2001-Feb-09
'       2009/02/03        ja-JP       2009-Feb-03
'       01/2009/03        ja-JP       2009-Jan-03
'       01/02/2009        ja-JP       2009-Jan-02
'       21/02/09          ja-JP       2021-Feb-09
'       01/22/09          ja-JP       FormatException
'       01/02/23          ja-JP       2001-Feb-23

備註

傳回值是叫用的結果DateTime.Parse(String, IFormatProvider)方法valueThe return value is the result of invoking the DateTime.Parse(String, IFormatProvider) method on value.

providerIFormatProvider取得的執行個體DateTimeFormatInfo物件。provider is an IFormatProvider instance that obtains a DateTimeFormatInfo object. DateTimeFormatInfo物件提供特定文化特性格式資訊valueThe DateTimeFormatInfo object provides culture-specific information about the format of value. 如果providernull,則DateTimeFormatInfo會使用目前的文化特性。If provider is null, the DateTimeFormatInfo for the current culture is used.

如果您不想處理的例外狀況,如果轉換失敗,您可以呼叫DateTime.TryParse方法改為。If you prefer not to handle an exception if the conversion fails, you can call the DateTime.TryParse method instead. 它會傳回Boolean值,指出轉換是否成功或失敗。It returns a Boolean value that indicates whether the conversion succeeded or failed.

另請參閱

ToDateTime(UInt64) ToDateTime(UInt64) ToDateTime(UInt64) ToDateTime(UInt64)

重要

此 API 不符合 CLS 規範。

呼叫這個方法一律會擲回 InvalidCastExceptionCalling this method always throws InvalidCastException.

public:
 static DateTime ToDateTime(System::UInt64 value);
[System.CLSCompliant(false)]
public static DateTime ToDateTime (ulong value);
static member ToDateTime : uint64 -> DateTime
Public Shared Function ToDateTime (value As ULong) As DateTime

參數

value
UInt64 UInt64 UInt64 UInt64

要轉換之 64 位元不帶正負號的整數。The 64-bit unsigned integer to convert.

傳回

不支援這個轉換。This conversion is not supported. 沒有傳回值。No value is returned.

例外狀況

不支援這個轉換。This conversion is not supported.

另請參閱

ToDateTime(Object, IFormatProvider) ToDateTime(Object, IFormatProvider) ToDateTime(Object, IFormatProvider) ToDateTime(Object, IFormatProvider)

使用指定之特定文化特性格式資訊,將指定之物件的值轉換為 DateTime 物件。Converts the value of the specified object to a DateTime object, using the specified culture-specific formatting information.

public:
 static DateTime ToDateTime(System::Object ^ value, IFormatProvider ^ provider);
public static DateTime ToDateTime (object value, IFormatProvider provider);
static member ToDateTime : obj * IFormatProvider -> DateTime
Public Shared Function ToDateTime (value As Object, provider As IFormatProvider) As DateTime

參數

value
Object Object Object Object

實作 IConvertible 介面的物件。An object that implements the IConvertible interface.

provider
IFormatProvider IFormatProvider IFormatProvider IFormatProvider

物件,提供特定文化特性格式資訊。An object that supplies culture-specific formatting information.

傳回

value 值相等的日期和時間;如果 MinValuevalue,則為與 null 相等的日期和時間。The date and time equivalent of the value of value, or the date and time equivalent of MinValue if value is null.

例外狀況

value 不是有效的日期和時間值。value is not a valid date and time value.

value 未實作 IConvertible 介面。value does not implement the IConvertible interface.

-或--or- 不支援轉換。The conversion is not supported.

範例

下列範例會定義自訂格式提供者CustomProvider,其GetFormat方法將訊息輸出至主控台,它已叫用,則會傳回DateTimeFormatInfo文化特性名稱做為參數傳遞至其類別的物件建構函式。The following example defines a custom format provider, CustomProvider, whose GetFormat method outputs a message to the console that it has been invoked, and then returns the DateTimeFormatInfo object of the culture whose name was passed as a parameter to its class constructor. 每一種CustomProvider物件用來將物件陣列中的項目轉換成日期和時間值。Each of these CustomProvider objects is used to convert the elements in an object array to date and time values. 輸出會指出CustomProvider物件會在轉換時,才的型別value參數是StringThe output indicates that the CustomProvider object is used in the conversion only when the type of the value parameter is a String.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string[] cultureNames = { "en-US", "hu-HU", "pt-PT" };
      object[] objects = { 12, 17.2, false, new DateTime(2010, 1, 1), "today", 
                           new System.Collections.ArrayList(), 'c', 
                           "05/10/2009 6:13:18 PM", "September 8, 1899" };
      
      foreach (string cultureName in cultureNames)
      {
         Console.WriteLine("{0} culture:", cultureName);
         CustomProvider provider = new CustomProvider(cultureName);
         foreach (object obj in objects)
         {            
            try {
               DateTime dateValue = Convert.ToDateTime(obj, provider);      
               Console.WriteLine("{0} --> {1}", obj, 
                                 dateValue.ToString(new CultureInfo(cultureName)));
            }
            catch (FormatException) {
               Console.WriteLine("{0} --> Bad Format", obj);
            }   
            catch (InvalidCastException) {
               Console.WriteLine("{0} --> Conversion Not Supported", obj);
            }
         }
         Console.WriteLine();
      }
   }
}

public class CustomProvider : IFormatProvider
{
   private string cultureName;
   
   public CustomProvider(string cultureName)
   {
      this.cultureName = cultureName;
   }
   
   public object GetFormat(Type formatType)
   {
      if (formatType == typeof(DateTimeFormatInfo))
      {
         Console.Write("(CustomProvider retrieved.) ");
         return new CultureInfo(cultureName).GetFormat(formatType);
      }
      else
      {
         return null;
      }   
   }
}
// The example displays the following output:
//    en-US culture:
//    12 --> Conversion Not Supported
//    17.2 --> Conversion Not Supported
//    False --> Conversion Not Supported
//    1/1/2010 12:00:00 AM --> 1/1/2010 12:00:00 AM
//    (CustomProvider retrieved.) today --> Bad Format
//    System.Collections.ArrayList --> Conversion Not Supported
//    c --> Conversion Not Supported
//    (CustomProvider retrieved.) 05/10/2009 6:13:18 PM --> 5/10/2009 6:13:18 PM
//    (CustomProvider retrieved.) September 8, 1899 --> 9/8/1899 12:00:00 AM
//    
//    hu-HU culture:
//    12 --> Conversion Not Supported
//    17.2 --> Conversion Not Supported
//    False --> Conversion Not Supported
//    1/1/2010 12:00:00 AM --> 2010. 01. 01. 0:00:00
//    (CustomProvider retrieved.) today --> Bad Format
//    System.Collections.ArrayList --> Conversion Not Supported
//    c --> Conversion Not Supported
//    (CustomProvider retrieved.) 05/10/2009 6:13:18 PM --> 2009. 05. 10. 18:13:18
//    (CustomProvider retrieved.) September 8, 1899 --> 1899. 09. 08. 0:00:00
//    
//    pt-PT culture:
//    12 --> Conversion Not Supported
//    17.2 --> Conversion Not Supported
//    False --> Conversion Not Supported
//    1/1/2010 12:00:00 AM --> 01-01-2010 0:00:00
//    (CustomProvider retrieved.) today --> Bad Format
//    System.Collections.ArrayList --> Conversion Not Supported
//    c --> Conversion Not Supported
//    (CustomProvider retrieved.) 05/10/2009 6:13:18 PM --> 05-10-2009 18:13:18
//    (CustomProvider retrieved.) September 8, 1899 --> 08-09-1899 0:00:00
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim cultureNames() As String = { "en-US", "hu-HU", "pt-PT" }
      Dim objects() As Object = { 12, 17.2, False, #1/1/2010#, "today", _
                                  New System.Collections.ArrayList(), "c"c, _
                                  "05/10/2009 6:13:18 PM", "September 8, 1899" }
      
      For Each cultureName As String In cultureNames
         Console.WriteLine("{0} culture:", cultureName)
         Dim provider As New CustomProvider(cultureName)
         For Each obj As Object In objects
            Try
               Dim dateValue As Date = Convert.ToDateTime(obj, provider)      
               Console.WriteLine("{0} --> {1}", obj, _
                                 dateValue.ToString(New CultureInfo(cultureName)))
            Catch e As FormatException
               Console.WriteLine("{0} --> Bad Format", obj)
            Catch e As InvalidCastException
               Console.WriteLine("{0} --> Conversion Not Supported", obj)
            End Try
         Next
         Console.WriteLine()
      Next
   End Sub
End Module

Public Class CustomProvider : Implements IFormatProvider
   Private cultureName As String
   
   Public Sub New(cultureName As String)
      Me.cultureName = cultureName
   End Sub
   
   Public Function GetFormat(formatType As Type) As Object _
          Implements IFormatProvider.GetFormat
      If formatType Is GetType(DateTimeFormatInfo) Then
         Console.Write("(CustomProvider retrieved.) ")
         Return New CultureInfo(cultureName).GetFormat(formatType)
      Else
         Return Nothing
      End If   
   End Function
End Class
' The example displays the following output:
'    en-US culture:
'    12 --> Conversion Not Supported
'    17.2 --> Conversion Not Supported
'    False --> Conversion Not Supported
'    1/1/2010 12:00:00 AM --> 1/1/2010 12:00:00 AM
'    (CustomProvider retrieved.) today --> Bad Format
'    System.Collections.ArrayList --> Conversion Not Supported
'    c --> Conversion Not Supported
'    (CustomProvider retrieved.) 05/10/2009 6:13:18 PM --> 5/10/2009 6:13:18 PM
'    (CustomProvider retrieved.) September 8, 1899 --> 9/8/1899 12:00:00 AM
'    
'    hu-HU culture:
'    12 --> Conversion Not Supported
'    17.2 --> Conversion Not Supported
'    False --> Conversion Not Supported
'    1/1/2010 12:00:00 AM --> 2010. 01. 01. 0:00:00
'    (CustomProvider retrieved.) today --> Bad Format
'    System.Collections.ArrayList --> Conversion Not Supported
'    c --> Conversion Not Supported
'    (CustomProvider retrieved.) 05/10/2009 6:13:18 PM --> 2009. 05. 10. 18:13:18
'    (CustomProvider retrieved.) September 8, 1899 --> 1899. 09. 08. 0:00:00
'    
'    pt-PT culture:
'    12 --> Conversion Not Supported
'    17.2 --> Conversion Not Supported
'    False --> Conversion Not Supported
'    1/1/2010 12:00:00 AM --> 01-01-2010 0:00:00
'    (CustomProvider retrieved.) today --> Bad Format
'    System.Collections.ArrayList --> Conversion Not Supported
'    c --> Conversion Not Supported
'    (CustomProvider retrieved.) 05/10/2009 6:13:18 PM --> 05-10-2009 18:13:18
'    (CustomProvider retrieved.) September 8, 1899 --> 08-09-1899 0:00:00

備註

傳回值是叫用的結果IConvertible.ToDateTime方法的基礎類型valueThe return value is the result of invoking the IConvertible.ToDateTime method of the underlying type of value.

provider 可讓使用者指定的內容相關的特定文化特性的轉換資訊valueprovider enables the user to specify culture-specific conversion information about the contents of value. 例如,如果valueString表示的日期,provider可能會提供用來代表該日期的標記法的特定文化特性資訊。For example, if value is a String that represents a date, provider could supply culture-specific information about the notation used to represent that date. provider 轉換涉及value執行階段類型,是否valueString,或如果value是使用者定義類型的IConvertible.ToDateTime實作會使用providerprovider is involved in the conversion of value if the runtime type of value is a String, or if value is a user-defined type whose IConvertible.ToDateTime implementation makes use of provider. 執行階段類型,是否valueStringprovidernull,則CultureInfo物件,表示目前執行緒文化特性用。If the runtime type of value is String and provider is null, the CultureInfo object that represents the current thread culture is used.

另請參閱

ToDateTime(SByte) ToDateTime(SByte) ToDateTime(SByte) ToDateTime(SByte)

重要

此 API 不符合 CLS 規範。

呼叫這個方法一律會擲回 InvalidCastExceptionCalling this method always throws InvalidCastException.

public:
 static DateTime ToDateTime(System::SByte value);
[System.CLSCompliant(false)]
public static DateTime ToDateTime (sbyte value);
static member ToDateTime : sbyte -> DateTime
Public Shared Function ToDateTime (value As SByte) As DateTime

參數

value
SByte SByte SByte SByte

要轉換的 8 位元帶正負號的整數。The 8-bit signed integer to convert.

傳回

不支援這個轉換。This conversion is not supported. 沒有傳回值。No value is returned.

例外狀況

不支援這個轉換。This conversion is not supported.

另請參閱

ToDateTime(UInt32) ToDateTime(UInt32) ToDateTime(UInt32) ToDateTime(UInt32)

重要

此 API 不符合 CLS 規範。

呼叫這個方法一律會擲回 InvalidCastExceptionCalling this method always throws InvalidCastException.

public:
 static DateTime ToDateTime(System::UInt32 value);
[System.CLSCompliant(false)]
public static DateTime ToDateTime (uint value);
static member ToDateTime : uint32 -> DateTime
Public Shared Function ToDateTime (value As UInteger) As DateTime

參數

value
UInt32 UInt32 UInt32 UInt32

要轉換之 32 位元不帶正負號的整數。The 32-bit unsigned integer to convert.

傳回

不支援這個轉換。This conversion is not supported. 沒有傳回值。No value is returned.

例外狀況

不支援這個轉換。This conversion is not supported.

另請參閱

ToDateTime(Object) ToDateTime(Object) ToDateTime(Object) ToDateTime(Object)

將指定之物件的值轉換為 DateTime 物件。Converts the value of the specified object to a DateTime object.

public:
 static DateTime ToDateTime(System::Object ^ value);
public static DateTime ToDateTime (object value);
static member ToDateTime : obj -> DateTime
Public Shared Function ToDateTime (value As Object) As DateTime

參數

value
Object Object Object Object

實作 IConvertible 介面的物件,或是 nullAn object that implements the IConvertible interface, or null.

傳回

value 值相等的日期和時間;如果 MinValuevalue,則為與 null 相等的日期和時間。The date and time equivalent of the value of value, or a date and time equivalent of MinValue if value is null.

例外狀況

value 不是有效的日期和時間值。value is not a valid date and time value.

value 未實作 IConvertible 介面。value does not implement the IConvertible interface.

-或--or- 不支援轉換。The conversion is not supported.

範例

下列範例會呼叫ToDateTime(Object)具有各種不同的方法Object變數。The following example calls the ToDateTime(Object) method with a variety of Object variables.

using System;

public class ConversionToDateTime
{
   public static void Main()
   {
      // Try converting an integer.
      int number = 16352;
      ConvertToDateTime(number);
      
      // Convert a null.
      object obj = null;
      ConvertToDateTime(obj);
      
      // Convert a non-date string.
      string nonDateString = "monthly";
      ConvertToDateTime(nonDateString);
      
      // Try to convert various date strings.
      string dateString; 
      dateString = "05/01/1996";
      ConvertToDateTime(dateString);
      dateString = "Tue Apr 28, 2009";
      ConvertToDateTime(dateString);
      dateString = "06 July 2008 7:32:47 AM";
      ConvertToDateTime(dateString);
      dateString = "17:32:47.003";
      ConvertToDateTime(dateString);
   }

   private static void ConvertToDateTime(object value)
   {
      DateTime convertedDate;
      try {
         convertedDate = Convert.ToDateTime(value);
         Console.WriteLine("'{0}' converts to {1}.", value, convertedDate);
      }
      catch (FormatException) {
         Console.WriteLine("'{0}' is not in the proper format.", value);
      }   
      catch (InvalidCastException) {
         Console.WriteLine("Conversion of the {0} '{1}' is not supported", 
                           value.GetType().Name, value);
      }
   }
}
// The example displays the following output:
//       Conversion of the Int32 '16352' is not supported
//       '' converts to 1/1/0001 12:00:00 AM.
//       'monthly' is not in the proper format.
//       '05/01/1996' converts to 5/1/1996 12:00:00 AM.
//       'Tue Apr 28, 2009' converts to 4/28/2009 12:00:00 AM.
//       '06 July 2008 7:32:47 AM' converts to 7/6/2008 7:32:47 AM.
//       '17:32:47.003' converts to 5/28/2008 5:32:47 PM.
Module ConversionToDateTime
   Public Sub Main()
      ' Try converting an integer.
      Dim number As Integer = 16352
      ConvertToDateTime(number)
      
      ' Convert a null.
      Dim obj As Object = Nothing
      ConvertToDateTime(obj)
      
      ' Convert a non-date string.
      Dim nonDateString As String = "monthly"
      ConvertToDateTime(nonDateString)
      
      ' Try to convert various dates.
      Dim dateString As String 
      dateString = "05/01/1996"
      ConvertToDateTime(dateString)
      dateString = "Tue Apr 28, 2009"
      ConvertToDateTime(dateString)
      dateString = "06 July 2008 7:32:47 AM"
      ConvertToDateTime(dateString)
      dateString = "17:32:47.003"
      ConvertToDateTime(dateString)
   End Sub
   
   Private Sub ConvertToDateTime(value As Object)
      Dim convertedDate As Date
      Try
         convertedDate = Convert.ToDateTime(value)
         Console.WriteLine("'{0}' converts to {1}.", value, convertedDate)
      Catch e As FormatException
         Console.WriteLine("'{0}' is not in the proper format.", value)
      Catch e As InvalidCastException
         Console.WriteLine("Conversion of the {0} '{1}' is not supported", _
                           value.GetType().Name, value)
      End Try
   End Sub
End Module
' The example displays the following output:
'       Conversion of the Int32 '16352' is not supported
'       '' converts to 1/1/0001 12:00:00 AM.
'       'monthly' is not in the proper format.
'       '05/01/1996' converts to 5/1/1996 12:00:00 AM.
'       'Tue Apr 28, 2009' converts to 4/28/2009 12:00:00 AM.
'       '06 July 2008 7:32:47 AM' converts to 7/6/2008 7:32:47 AM.
'       '17:32:47.003' converts to 5/28/2008 5:32:47 PM.

備註

若要成功,執行階段型別轉換value參數必須是DateTimeString,或value必須是nullFor the conversion to succeed, the runtime type of the value parameter must be either a DateTime or a String, or value must be null. 否則,此方法會擲回InvalidCastExceptionOtherwise, the method throws an InvalidCastException. 此外,如果value是一個字串,它必須包含在目前的文化特性的日期和時間值的有效表示法或FormatException就會擲回。In addition, if value is a string, it must contain a valid representation of a date and time value in the current culture or a FormatException is thrown.

傳回值是叫用的結果IConvertible.ToDateTime方法的基礎類型valueThe return value is the result of invoking the IConvertible.ToDateTime method of the underlying type of value.

ToDateTime(Double) ToDateTime(Double) ToDateTime(Double) ToDateTime(Double)

呼叫這個方法一律會擲回 InvalidCastExceptionCalling this method always throws InvalidCastException.

public:
 static DateTime ToDateTime(double value);
public static DateTime ToDateTime (double value);
static member ToDateTime : double -> DateTime
Public Shared Function ToDateTime (value As Double) As DateTime

參數

value
Double Double Double Double

要轉換的雙精確度浮點數值。The double-precision floating-point value to convert.

傳回

不支援這個轉換。This conversion is not supported. 沒有傳回值。No value is returned.

例外狀況

不支援這個轉換。This conversion is not supported.

另請參閱

ToDateTime(Int32) ToDateTime(Int32) ToDateTime(Int32) ToDateTime(Int32)

呼叫這個方法一律會擲回 InvalidCastExceptionCalling this method always throws InvalidCastException.

public:
 static DateTime ToDateTime(int value);
public static DateTime ToDateTime (int value);
static member ToDateTime : int -> DateTime
Public Shared Function ToDateTime (value As Integer) As DateTime

參數

value
Int32 Int32 Int32 Int32

要轉換的 32 位元帶正負號的整數。The 32-bit signed integer to convert.

傳回

不支援這個轉換。This conversion is not supported. 沒有傳回值。No value is returned.

例外狀況

不支援這個轉換。This conversion is not supported.

另請參閱

ToDateTime(Boolean) ToDateTime(Boolean) ToDateTime(Boolean) ToDateTime(Boolean)

呼叫這個方法一律會擲回 InvalidCastExceptionCalling this method always throws InvalidCastException.

public:
 static DateTime ToDateTime(bool value);
public static DateTime ToDateTime (bool value);
static member ToDateTime : bool -> DateTime
Public Shared Function ToDateTime (value As Boolean) As DateTime

參數

value
Boolean Boolean Boolean Boolean

要轉換的布林值。The Boolean value to convert.

傳回

不支援這個轉換。This conversion is not supported. 沒有傳回值。No value is returned.

例外狀況

不支援這個轉換。This conversion is not supported.

另請參閱

ToDateTime(Byte) ToDateTime(Byte) ToDateTime(Byte) ToDateTime(Byte)

呼叫這個方法一律會擲回 InvalidCastExceptionCalling this method always throws InvalidCastException.

public:
 static DateTime ToDateTime(System::Byte value);
public static DateTime ToDateTime (byte value);
static member ToDateTime : byte -> DateTime
Public Shared Function ToDateTime (value As Byte) As DateTime

參數

value
Byte Byte Byte Byte

要轉換之 8 位元不帶正負號的整數。The 8-bit unsigned integer to convert.

傳回

不支援這個轉換。This conversion is not supported. 沒有傳回值。No value is returned.

例外狀況

不支援這個轉換。This conversion is not supported.

另請參閱

ToDateTime(Char) ToDateTime(Char) ToDateTime(Char) ToDateTime(Char)

呼叫這個方法一律會擲回 InvalidCastExceptionCalling this method always throws InvalidCastException.

public:
 static DateTime ToDateTime(char value);
public static DateTime ToDateTime (char value);
static member ToDateTime : char -> DateTime
Public Shared Function ToDateTime (value As Char) As DateTime

參數

value
Char Char Char Char

要轉換的 Unicode 字元。The Unicode character to convert.

傳回

不支援這個轉換。This conversion is not supported. 沒有傳回值。No value is returned.

例外狀況

不支援這個轉換。This conversion is not supported.

另請參閱

ToDateTime(Int64) ToDateTime(Int64) ToDateTime(Int64) ToDateTime(Int64)

呼叫這個方法一律會擲回 InvalidCastExceptionCalling this method always throws InvalidCastException.

public:
 static DateTime ToDateTime(long value);
public static DateTime ToDateTime (long value);
static member ToDateTime : int64 -> DateTime
Public Shared Function ToDateTime (value As Long) As DateTime

參數

value
Int64 Int64 Int64 Int64

要轉換的 64 位元帶正負號的整數。The 64-bit signed integer to convert.

傳回

不支援這個轉換。This conversion is not supported. 沒有傳回值。No value is returned.

例外狀況

不支援這個轉換。This conversion is not supported.

另請參閱

ToDateTime(Decimal) ToDateTime(Decimal) ToDateTime(Decimal) ToDateTime(Decimal)

呼叫這個方法一律會擲回 InvalidCastExceptionCalling this method always throws InvalidCastException.

public:
 static DateTime ToDateTime(System::Decimal value);
public static DateTime ToDateTime (decimal value);
static member ToDateTime : decimal -> DateTime
Public Shared Function ToDateTime (value As Decimal) As DateTime

參數

value
Decimal Decimal Decimal Decimal

要轉換的數字。The number to convert.

傳回

不支援這個轉換。This conversion is not supported. 沒有傳回值。No value is returned.

例外狀況

不支援這個轉換。This conversion is not supported.

ToDateTime(Int16) ToDateTime(Int16) ToDateTime(Int16) ToDateTime(Int16)

呼叫這個方法一律會擲回 InvalidCastExceptionCalling this method always throws InvalidCastException.

public:
 static DateTime ToDateTime(short value);
public static DateTime ToDateTime (short value);
static member ToDateTime : int16 -> DateTime
Public Shared Function ToDateTime (value As Short) As DateTime

參數

value
Int16 Int16 Int16 Int16

要轉換的 16 位元帶正負號的整數。The 16-bit signed integer to convert.

傳回

不支援這個轉換。This conversion is not supported. 沒有傳回值。No value is returned.

例外狀況

不支援這個轉換。This conversion is not supported.

另請參閱

ToDateTime(DateTime) ToDateTime(DateTime) ToDateTime(DateTime) ToDateTime(DateTime)

傳回指定的 DateTime 物件;不會執行實際的轉換。Returns the specified DateTime object; no actual conversion is performed.

public:
 static DateTime ToDateTime(DateTime value);
public static DateTime ToDateTime (DateTime value);
static member ToDateTime : DateTime -> DateTime
Public Shared Function ToDateTime (value As DateTime) As DateTime

參數

value
DateTime DateTime DateTime DateTime

日期和時間值。A date and time value.

傳回

value 會原封不動地傳回。value is returned unchanged.

適用於