C# Convert ToDateTime(String, IFormatProvider)

Description

Convert ToDateTime(String, IFormatProvider) converts the specified string representation of a number to an equivalent date and time, using the specified culture-specific formatting information.

Syntax

Convert.ToDateTime(String, IFormatProvider) has the following syntax.


public static DateTime ToDateTime(
  string value,
  IFormatProvider provider
)

Parameters

Convert.ToDateTime(String, IFormatProvider) has the following parameters.

  • value - A string that contains a date and time to convert.
  • provider - An object that supplies culture-specific formatting information.

Returns

Convert.ToDateTime(String, IFormatProvider) method returns The date and time equivalent of the value of value, or the date and time equivalent of DateTime.MinValue if value is null.

Example

The following example converts string representations of date values with the ToDateTime method, using an IFormatProvider object.


using System;/*from  w w w .ja  v  a2 s  . c  om*/
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", "2014/02/03",  "01/2014/03", 
                               "01/02/2014", "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();
      }
   }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version