Freigeben über


DateTime.Parse Method (String, IFormatProvider)

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Converts the specified string representation of a date and time to its DateTime equivalent using the specified culture-specific format information.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

Syntax

'Declaration
Public Shared Function Parse ( _
    s As String, _
    provider As IFormatProvider _
) As DateTime
public static DateTime Parse(
    string s,
    IFormatProvider provider
)

Parameters

  • s
    Type: System.String
    A string that contains a date and time to convert.

Return Value

Type: System.DateTime
An object that is equivalent to the date and time contained in the s parameter, as specified by the provider parameter.

Exceptions

Exception Condition
ArgumentNullException

s is nulla null reference (Nothing in Visual Basic).

FormatException

s does not contain a valid string representation of a date and time.

Remarks

The string s is parsed using formatting information in the DateTimeFormatInfo object that is supplied either explicitly or implicitly by the provider parameter. The s parameter must contain the representation of a date and time in one of the patterns recognized by the DateTimeFormatInfo object available from provider.

Important noteImportant Note:

Because the string representation of a date and time must conform to a recognized pattern, applications should always use exception handling when calling the Parse(String) method to parse user input.

This method attempts to parse s completely and avoid throwing a FormatException. It ignores unrecognized data if possible and fills in missing month, day, and year information with the current date. If s contains only a date and no time, this method assumes 12:00 midnight. If s contains only a time and no date, this method assumes the current date. If s includes a date component with a two-digit year, it is converted to a year in the provider parameter's current calendar based on the value of the Calendar.TwoDigitYearMax property. Any leading, inner, or trailing white space character in s is ignored. The date and time can be bracketed with a pair of leading and trailing NUMBER SIGN characters ('#', U+0023), and can be trailed with one or more NULL characters (U+0000).

The format of s is defined by the provider parameter, which can be any of the following:

If provider is nulla null reference (Nothing in Visual Basic), the current culture is used.

In most cases, the Parse(String) method returns a DateTime value whose Kind property is DateTimeKind.Unspecified. However, if the string to be parsed contains time zone information as defined by ISO 8601 or if it includes the older GMT designator, the Parse(String) method performs any necessary time conversion and returns a DateTime value whose date and time reflects the local time and whose Kind property is DateTimeKind.Local.

Because the DateTime.Parse(String, IFormatProvider) method tries to parse the string representation of a date and time using the formatting rules of the provider parameter, trying to parse a particular string across different cultures can either fail or return different results. If a specific date and time format will be parsed across different locales, use one of the overloads of the ParseExact method and provide a format specifier.

Parsing Non-Standard Cultures

If you parse a date and time string using a CultureInfo or DateTimeFormatInfo object which includes customized settings that are different from those of a standard culture, use the ParseExact method instead of the Parse method to improve the probability that the parse operation will succeed. A non-standard date and time string can be complicated and difficult to parse. The Parse method tries to parse a string with several implicit parse patterns, all of which might fail. In contrast, the ParseExact method requires you to explicitly designate one or more exact parse patterns that are likely to succeed.

Examples

The following example demonstrates the DateTime.Parse(String, IFormatProvider) method. It also illustrates the fact that string representations of a single date can be interpreted differently across different cultures.

Imports System.Globalization

Module Example
   Public Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)
      ' 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 As CultureInfo In cultures
         Dim dateValue As Date
         outputBlock.Text += String.Format("Attempted conversions using {0} culture.", culture.Name) & vbCrLf
         For Each dateString As String In dateStrings
            Try
               dateValue = Date.Parse(dateString, culture)
               outputBlock.Text += String.Format("   Converted '{0}' to {1}.", _
                                 dateString, dateValue.ToString("f", culture)) & vbCrLf
            Catch e As FormatException
               outputBlock.Text += String.Format("   Unable to convert '{0}' for culture {1}.", _
                                 dateString, culture.Name) & vbCrLf
            End Try
         Next
         outputBlock.Text &= vbCrLf
      Next
   End Sub
End Module
' The example displays the following output:
'       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.
using System;
using System.Globalization;

public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      // 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;
         outputBlock.Text += String.Format("Attempted conversions using {0} culture.",
                           culture.Name) + "\n";
         foreach (string dateString in dateStrings)
         {
            try
            {
               dateValue = DateTime.Parse(dateString, culture);
               outputBlock.Text += String.Format("   Converted '{0}' to {1}.",
                                 dateString, dateValue.ToString("f", culture)) + "\n";
            }
            catch (FormatException)
            {
               outputBlock.Text += String.Format("   Unable to convert '{0}' for culture {1}.",
                                 dateString, culture.Name) + "\n";
            }
         }
         outputBlock.Text += "\n";
      }
   }
}
// The example displays the following output:
//       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.

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.