.NET Framework Class Library DateTime..::.Parse Method (String, IFormatProvider, DateTimeStyles) Updated: October 2010 Converts the specified string representation of a date and time to its DateTime equivalent using the specified culture-specific format information and formatting style.
Namespace:
System
Assembly:
mscorlib (in mscorlib.dll)

Syntax
Public Shared Function Parse ( _
s As String, _
provider As IFormatProvider, _
styles As DateTimeStyles _
) As DateTime
public static DateTime Parse(
string s,
IFormatProvider provider,
DateTimeStyles styles
)
public:
static DateTime Parse(
String^ s,
IFormatProvider^ provider,
DateTimeStyles styles
)
static member Parse :
s:string *
provider:IFormatProvider *
styles:DateTimeStyles -> DateTime
Parameters- s
- Type: System..::.String
A string containing a date and time to convert.
- provider
- Type: System..::.IFormatProvider
An object that supplies culture-specific formatting information about s.
- styles
- Type: System.Globalization..::.DateTimeStyles
A bitwise combination of the enumeration values that indicates the style elements that can be present in s for the parse operation to succeed and that defines how to interpret the parsed date in relation to the current time zone or the current date. A typical value to specify is DateTimeStyles..::.None.
Return ValueType: System..::.DateTimeAn object that is equivalent to the date and time contained in s, as specified by provider and styles.

Exceptions

Remarks
This method parses a string with two elements that can appear in any order and are delimited by white space. These two elements are shown in the following table. Date and time element | Example (en-US culture) |
|---|
<Date> | "2/10/2009" | <Time> | "1:02:03 PM" |
Either <Date> or <Time> but not both elements can be absent from s. In addition, s can contain time zone information. If <Time> is missing, its default value is 12:00:00 A.M. If <Date> is missing, its default value is the current day. However, if <Date> is missing and styles includes the NoCurrentDateDefault value, its date is assumed to be January 1, 0001. Each element can also be enclosed by leading or trailing white space and can even include inner white space (such as "6: 00: 00"). A time zone specifier (such as Z or GMT to indicate Coordinated Universal Time (UTC)) can also be present. In addition, s can include a time zone offset (such as "2008-10-1T6:00:32-8:00"). In this case, the format of s must conform to the ISO 8601 standard. The format of s is defined by the provider parameter, which can be any of the following: If provider is nullNothingnullptra null reference (Nothing in Visual Basic), the CultureInfo object for the current culture is used. The styles parameter consists of one or more members of the DateTimeStyles enumeration that define how s is to be interpreted and how the parse operation is to convert s to a date and time. The following table describes the effect of each member on the parse operation. DateTimeStyles member | Description |
|---|
AdjustToUniversal
| Parses s and, if necessary, converts it to UTC. If s includes a time zone offset, or if s contains no time zone information but styles includes the DateTimeStyles..::.AssumeLocal flag, the method parses the string, calls ToUniversalTime to convert the returned DateTime value to UTC, and sets the Kind property to DateTimeKind..::.Utc. If s indicates that it represents UTC, or if s does not contain time zone information but styles includes the DateTimeStyles..::.AssumeUniversal flag, the method parses the string, performs no time zone conversion on the returned DateTime value, and sets the Kind property to DateTimeKind..::.Utc. In all other cases, the flag has no effect. |
AllowInnerWhite
| Although valid, this value is ignored. Inner white space is permitted in the date and time elements of s. |
AllowLeadingWhite
| Although valid, this value is ignored. Leading white space is permitted in the date and time elements of s. |
AllowTrailingWhite
| Although valid, this value is ignored. Trailing white space is permitted in the date and time elements of s. |
AllowWhiteSpaces
| Specifies that s may contain leading, inner, and trailing white spaces. This is the default behavior. It cannot be overridden by supplying a more restrictive DateTimeStyles enumeration value such as DateTimeStyles..::.None. |
AssumeLocal
| Specifies that if s lacks any time zone information, it is assumed to represent a local time. Unless the DateTimeStyles..::.AdjustToUniversal flag is present, the Kind property of the returned DateTime value is set to DateTimeKind..::.Local. |
AssumeUniversal
| Specifies that if s lacks any time zone information, it is assumed to represent UTC. Unless the DateTimeStyles..::.AdjustToUniversal flag is present, the method converts the returned DateTime value from UTC to local time and sets its Kind property to DateTimeKind..::.Local. |
None
| Although valid, this value is ignored. |
RoundtripKind
| For strings that contain time zone information, tries to prevent the conversion of a date and time string to a DateTime value that represents a local time with its Kind property set to DateTimeKind..::.Local. Typically, such a string is created by calling the DateTime..::.ToString(String) method using either the o, r, or u standard format specifiers. |
If s contains no time zone information, the DateTime..::.Parse(String, IFormatProvider, DateTimeStyles) method returns a DateTime value whose Kind property is DateTimeKind..::.Unspecified unless a styles flag indicates otherwise. If s includes time zone or time zone offset information, the DateTime..::.Parse(String, IFormatProvider, DateTimeStyles) method performs any necessary time conversion and returns one of the following: This behavior can be overridden by using the DateTimeStyles..::.RoundtripKind flag. The following example illustrates how the DateTimeStyles..::.RoundtripKind flag affects the parsing operation on DateTime values that are converted to strings using the o, r, or u format specifier.
Dim formattedDates() As String = { "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 As String In formattedDates
Console.WriteLine(formattedDate)
Dim roundtripDate As Date = Date.Parse(formattedDate, Nothing, _
DateTimeStyles.RoundtripKind)
Console.WriteLine(" With RoundtripKind flag: {0} {1} time.", _
roundtripDate, roundtripDate.Kind)
Dim noRoundtripDate As Date = Date.Parse(formattedDate, Nothing, _
DateTimeStyles.None)
Console.WriteLine(" Without RoundtripKind flag: {0} {1} time.", _
noRoundtripDate, noRoundtripDate.Kind)
Next
' The example displays the following output:
' 2008-09-15T09:30:41.7752486-07:00
' With RounndtripKind 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 RounndtripKind 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 RounndtripKind 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 RounndtripKind 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 RounndtripKind flag: 9/15/2008 9:30:41 AM Utc time.
' Without RoundtripKind flag: 9/15/2008 2:30:41 AM Local time.
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: {0} {1} time.",
roundtripDate, roundtripDate.Kind);
DateTime noRoundtripDate = DateTime.Parse(formattedDate, null,
DateTimeStyles.None);
Console.WriteLine(" Without RoundtripKind flag: {0} {1} time.",
noRoundtripDate, noRoundtripDate.Kind);
}
// 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.
Because the DateTime..::.Parse(String, IFormatProvider, DateTimeStyles) 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 fail. 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 Custom CulturesIf you parse a date and time string generated for a custom culture, use the ParseExact method instead of the Parse method to improve the probability that the parse operation will succeed. A custom culture date and time string can be complicated, and therefore difficult to parse. The Parse method attempts to parse a string with several implicit parse patterns, all of which might fail. The ParseExact method, in contrast, requires you to explicitly designate one or more exact parse patterns that are likely to succeed. For more information about custom cultures, see the System.Globalization..::.CultureAndRegionInfoBuilder class. Notes to CallersFormatting is influenced by properties of the current DateTimeFormatInfo object, which is supplied by the provider parameter. One reason the Parse method can unexpectedly throw FormatException is if the current DateTimeFormatInfo..::.DateSeparator and DateTimeFormatInfo..::.TimeSeparator properties are set to the same value.

Examples
The following example demonstrates the DateTime..::.Parse(String, IFormatProvider, DateTimeStyles) method.
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.
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.

Version Information
.NET FrameworkSupported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0 .NET Framework Client ProfileSupported in: 4, 3.5 SP1 Portable Class LibrarySupported in: Portable Class Library

Platforms
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role not supported), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

See Also

Change History
Date | History | Reason |
|---|
October 2010
| Removed mention of DateTimeFormatInfo.GetAllDateTimePatterns. |
Content bug fix.
|
|
Biblioteca de clases de .NET Framework DateTime..::.Parse (Método) (String, IFormatProvider, DateTimeStyles) Convierte la representación de cadena que se haya especificado para una fecha y hora en su DateTime equivalente, utilizando la información de formato específica de la referencia cultural y el estilo de formato especificados.
Espacio de nombres:
System
Ensamblado:
mscorlib (en mscorlib.dll)

Sintaxis
Public Shared Function Parse ( _
s As String, _
provider As IFormatProvider, _
styles As DateTimeStyles _
) As DateTime
public static DateTime Parse(
string s,
IFormatProvider provider,
DateTimeStyles styles
)
public:
static DateTime Parse(
String^ s,
IFormatProvider^ provider,
DateTimeStyles styles
)
static member Parse :
s:string *
provider:IFormatProvider *
styles:DateTimeStyles -> DateTime
Parámetros- s
- Tipo: System..::.String
Cadena que contiene una fecha y hora que se van a convertir.
- provider
- Tipo: System..::.IFormatProvider
Objeto que aporta información de formato específica de la referencia cultural acerca de s.
- styles
- Tipo: System.Globalization..::.DateTimeStyles
Una combinación bit a bit de los valores de enumeración que indica los elementos de estilo que pueden encontrarse en s para que la operación de análisis tenga éxito y define cómo interpretar la fecha analizada respecto a la zona horaria o la fecha actual. Un valor que se especifica de forma habitual es DateTimeStyles..::.None.
Valor devueltoTipo: System..::.DateTimeObjeto equivalente a la fecha y hora contenidas en s, tal como especifican provider y styles.

Excepciones
| Excepción | Condición |
|---|
| ArgumentNullException |
El valor de s es nullNothingnullptrreferencia null (Nothing en Visual Basic). | | FormatException |
s no contiene una representación de cadena válida de una fecha y hora. | | ArgumentException |
styles contiene una combinación no válida de valores de DateTimeStyles. Por ejemplo, AssumeLocal y AssumeUniversal. |

Comentarios
Este método analiza una cadena con dos elementos que pueden aparecer en cualquier orden y están delimitados por espacios en blanco. Estos dos elementos se muestran en la tabla siguiente. Elemento de fecha y hora | Ejemplo (referencia cultural en-US) |
|---|
<Fecha> | "2/10/2009" | <Hora> | "1:02:03 p.m." |
Los elementos <Fecha> u <Hora>, pero no ambos, pueden estar ausentes de s. Además, s puede incluir información de la zona horaria. Si falta <Hora>, su valor predeterminado es 12:00:00 a.m. Si falta <Fecha>, su valor predeterminado es el día de hoy. Sin embargo, si falta <Fecha> y styles incluye el valor NoCurrentDateDefault, se supone que la fecha es el 1 de enero de 0001. Cada elemento se puede agregar también llevando o arrastrando el espacio en blanco y pueden incluir un espacio en blanco interno (como "6: 00: 00"). Sin embargo, si falta <Fecha> y styles incluye el valor NoCurrentDateDefault, se da por supuesto que la fecha es el 1 de enero de 0001. Cada elemento puede estar encerrado entre espacios en blanco iniciales o finales e incluso puede contener espacios en blanco internos (como "6: 00: 00"). También puede estar presente un especificador de zona horaria (como Z o GMT para indicar la hora universal coordinada (UTC)). Además, s pueden incluir un desplazamiento de zona horaria (como "2008-10-1T6: 00:32-8:00"). En este caso, el formato de s debe cumplir la norma ISO 8601. El formato de s se define con el parámetro provider, que puede ser cualquiera de los siguientes: Si provider es nullNothingnullptrreferencia null (Nothing en Visual Basic), se usa el objeto CultureInfo de la actual referencia cultural. El parámetro styles consta de uno o varios miembros de la enumeración DateTimeStyles que definen el modo en que debe interpretarse s y el modo en que la operación de análisis debe convertir s en un valor de fecha y hora. En la tabla siguiente, se describe el efecto de la operación de análisis en cada miembro. Miembro DateTimeStyles | Descripción |
|---|
AdjustToUniversal
| Analiza s y, si es necesario, lo convierte en la hora UTC. Si s incluye un desplazamiento de zona horaria o si s no contiene ninguna información de zona horaria, pero styles incluye el marcador DateTimeStyles..::.AssumeLocal, el método analiza la cadena, llama a ToUniversalTime para convertir el valor DateTime devuelto en hora UTC y establece la propiedad Kind en DateTimeKind..::.Utc. Si s indica que representa la hora UTC o si s no contiene información de la zona horaria, pero styles incluye el marcador DateTimeStyles..::.AssumeUniversal, el método analiza la cadena, no realiza ninguna conversión de zona horaria en el valor DateTime devuelto y establece la propiedad Kind en DateTimeKind..::.Utc. En todos los demás casos, el marcador no tiene ningún efecto. |
AllowInnerWhite
| Aunque sea válido, este valor se pasa por alto. Se permite el espacio en blanco interno en los elementos de fecha y hora de s. |
AllowLeadingWhite
| Aunque sea válido, este valor se pasa por alto. Se permite el espacio en blanco inicial en los elementos de fecha y hora de s. |
AllowTrailingWhite
| Aunque sea válido, este valor se pasa por alto. Se permite el espacio en blanco final en los elementos de fecha y hora de s. |
AllowWhiteSpaces
| Especifica que s puede contener espacios en blanco iniciales, internos y finales. Éste es el comportamiento predeterminado. No se puede invalidar aunque se proporcione un valor de enumeración DateTimeStyles más restrictivo, como DateTimeStyles..::.None. |
AssumeLocal
| Especifica que, si s carece de cualquier información de zona horaria, se supone que representa una hora local. A menos que esté presente el marcador DateTimeStyles..::.AdjustToUniversal, la propiedad Kind del valor DateTime devuelto está establecida en DateTimeKind..::.Local. |
AssumeUniversal
| Especifica que si s carece de cualquier información de zona horaria, se supone que representa la hora UTC. A menos que esté presente el marcador DateTimeStyles..::.AdjustToUniversal, el método convierte el valor DateTime devuelto de hora UTC en la hora local y establece su propiedad Kind en DateTimeKind..::.Local. |
None
| Aunque sea válido, este valor se pasa por alto. |
RoundtripKind
| En el caso de las cadenas que contienen información de la zona horaria, intenta impedir la conversión de una cadena de fecha y hora en un valor DateTime que representa una hora local con su propiedad Kind establecida en DateTimeKind..::.Local. Normalmente, una cadena de este tipo se crea llamando al método DateTime..::.ToString(String) mediante los especificadores de forma estándar “o”, “r” o “u”. |
Si s no incluye información de zona horaria, el método DateTime..::.Parse(String, IFormatProvider, DateTimeStyles) devuelve un valor DateTime cuya propiedad Kind es DateTimeKind..::.Unspecified, a menos que un marcador styles indique lo contrario. Si s incluye información sobre la zona sobre el desplazamiento de zona horaria, el método DateTime..::.Parse(String, IFormatProvider, DateTimeStyles) realiza cualquier conversión de hora que sea necesaria y devuelve uno de los siguientes valores: Este comportamiento puede invalidarse mediante el marcador DateTimeStyles..::.RoundtripKind. En el ejemplo siguiente se muestra el modo en que el marcador DateTimeStyles..::.RoundtripKind afecta a la operación de análisis en valores de tipo DateTime convertidos en cadenas mediante el especificador de formato “o”, “r” o “u”.
Dim formattedDates() As String = { "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 As String In formattedDates
Console.WriteLine(formattedDate)
Dim roundtripDate As Date = Date.Parse(formattedDate, Nothing, _
DateTimeStyles.RoundtripKind)
Console.WriteLine(" With RoundtripKind flag: {0} {1} time.", _
roundtripDate, roundtripDate.Kind)
Dim noRoundtripDate As Date = Date.Parse(formattedDate, Nothing, _
DateTimeStyles.None)
Console.WriteLine(" Without RoundtripKind flag: {0} {1} time.", _
noRoundtripDate, noRoundtripDate.Kind)
Next
' The example displays the following output:
' 2008-09-15T09:30:41.7752486-07:00
' With RounndtripKind 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 RounndtripKind 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 RounndtripKind 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 RounndtripKind 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 RounndtripKind flag: 9/15/2008 9:30:41 AM Utc time.
' Without RoundtripKind flag: 9/15/2008 2:30:41 AM Local time.
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: {0} {1} time.",
roundtripDate, roundtripDate.Kind);
DateTime noRoundtripDate = DateTime.Parse(formattedDate, null,
DateTimeStyles.None);
Console.WriteLine(" Without RoundtripKind flag: {0} {1} time.",
noRoundtripDate, noRoundtripDate.Kind);
}
// 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.
Dado que el método DateTime..::.Parse(String, IFormatProvider, DateTimeStyles) intenta analizar la representación de cadena de una fecha y hora utilizando las reglas de formato del parámetro provider, el intento de analizar una cadena concreta en referencias culturales diferentes puede sufrir un error. Si un formato de fecha y hora concreto se va a analizar en configuraciones regionales diferentes, se debe usar una de las sobrecargas del método ParseExact y proporcionar un especificador de formato. Análisis de las referencias culturales personalizadasPara analizar una cadena de fecha y hora generada para una referencia cultural personalizada, utilice el método ParseExact, en lugar del método Parse, para que la probabilidad de que la operación de análisis se realice correctamente sea mayor. Una cadena de fecha y hora para una referencia cultural personalizada puede ser complicada y, por consiguiente, difícil de analizar. El método Parse intenta analizar la cadena con modelos implícitos de análisis, pero en todos se puede producir un error. Por el contrario, el método ParseExact exige que se designen explícitamente uno o varios modelos exactos de análisis que es muy probable que se ejecuten correctamente. Para obtener más información sobre las referencias culturales personalizadas, vea la clase System.Globalization..::.CultureAndRegionInfoBuilder. Notas para los llamadoresEl formato depende de las propiedades del objeto DateTimeFormatInfo actual, que es proporcionado por el parámetro provider. Una razón por la que el método Parse puede producir inesperadamente una excepción FormatException es que se establezca el mismo valor para las propiedades DateTimeFormatInfo..::.DateSeparator y DateTimeFormatInfo..::.TimeSeparator actuales.

Ejemplos
En el siguiente ejemplo se muestra el método DateTime..::.Parse(String, IFormatProvider, DateTimeStyles).
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.
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.

Información de versión
.NET FrameworkCompatible con: 4, 3.5, 3.0, 2.0, 1.1, 1.0 .NET Framework Client ProfileCompatible con: 4, 3.5 SP1 Compatible con:

Plataformas
Windows 7, Windows Vista SP1 o posterior, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (no se admite Server Core), Windows Server 2008 R2 (se admite Server Core con SP1 o posterior), Windows Server 2003 SP2
.NET Framework no admite todas las versiones de todas las plataformas. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.

Vea también

Historial de cambios
Fecha | Historial | Motivo |
|---|
Octubre de 2010
| Eliminada mención de DateTimeFormatInfo.GetAllDateTimePatterns. |
Corrección de errores de contenido.
|
|