DateTimeOffset.TryParse Método
Definição
Converte uma representação de cadeia de caracteres especificada de uma data e hora ao seu equivalente DateTimeOffset.Converts a specified string representation of a date and time to its DateTimeOffset equivalent.
Sobrecargas
| TryParse(String, IFormatProvider, DateTimeStyles, DateTimeOffset) |
Tenta converter a representação de cadeia de caracteres especificada de uma data e hora em seu DateTimeOffset equivalente e retorna um valor que indica se a conversão foi bem-sucedida.Tries to convert a specified string representation of a date and time to its DateTimeOffset equivalent, and returns a value that indicates whether the conversion succeeded. |
| TryParse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles, DateTimeOffset) |
Tenta converter a representação de intervalo especificada de uma data e hora em seu DateTimeOffset equivalente e retorna um valor que indica se a conversão foi bem-sucedida.Tries to convert a specified span representation of a date and time to its DateTimeOffset equivalent, and returns a value that indicates whether the conversion succeeded. |
| TryParse(String, DateTimeOffset) |
Tenta converter a representação de cadeia de caracteres especificada de uma data e hora em seu DateTimeOffset equivalente e retorna um valor que indica se a conversão foi bem-sucedida.Tries to converts a specified string representation of a date and time to its DateTimeOffset equivalent, and returns a value that indicates whether the conversion succeeded. |
| TryParse(ReadOnlySpan<Char>, DateTimeOffset) |
Tenta converter a representação de intervalo especificada de uma data e hora em seu DateTimeOffset equivalente e retorna um valor que indica se a conversão foi bem-sucedida.Tries to convert a specified span representation of a date and time to its DateTimeOffset equivalent, and returns a value that indicates whether the conversion succeeded. |
TryParse(String, IFormatProvider, DateTimeStyles, DateTimeOffset)
Tenta converter a representação de cadeia de caracteres especificada de uma data e hora em seu DateTimeOffset equivalente e retorna um valor que indica se a conversão foi bem-sucedida.Tries to convert a specified string representation of a date and time to its DateTimeOffset equivalent, and returns a value that indicates whether the conversion succeeded.
public:
static bool TryParse(System::String ^ input, IFormatProvider ^ formatProvider, System::Globalization::DateTimeStyles styles, [Runtime::InteropServices::Out] DateTimeOffset % result);
public static bool TryParse (string input, IFormatProvider formatProvider, System.Globalization.DateTimeStyles styles, out DateTimeOffset result);
public static bool TryParse (string? input, IFormatProvider? formatProvider, System.Globalization.DateTimeStyles styles, out DateTimeOffset? result);
static member TryParse : string * IFormatProvider * System.Globalization.DateTimeStyles * DateTimeOffset -> bool
Public Shared Function TryParse (input As String, formatProvider As IFormatProvider, styles As DateTimeStyles, ByRef result As DateTimeOffset) As Boolean
Parâmetros
- input
- String
Uma cadeia de caracteres que contém uma data e hora a ser convertida.A string that contains a date and time to convert.
- formatProvider
- IFormatProvider
Um objeto que fornece informações de formatação específicas à cultura sobre input.An object that provides culture-specific formatting information about input.
- styles
- DateTimeStyles
Um combinação bit a bit de valores de enumeração que indica o formato permitido de input.A bitwise combination of enumeration values that indicates the permitted format of input.
- result
- DateTimeOffset
Quando é retornado, esse método contém o valor DateTimeOffset equivalente à data e hora de input, caso a conversão seja bem-sucedida ou MinValue caso a conversão falhe.When the method returns, contains the DateTimeOffset value equivalent to the date and time of input, if the conversion succeeded, or MinValue, if the conversion failed. A conversão falhará se o parâmetro input for null ou não contiver uma representação de cadeia de caracteres válida de uma data e hora.The conversion fails if the input parameter is null or does not contain a valid string representation of a date and time. Este parâmetro é passado não inicializado.This parameter is passed uninitialized.
Retornos
true caso o parâmetro input seja convertido com êxito; do contrário, false.true if the input parameter is successfully converted; otherwise, false.
Exceções
styles inclui um valor DateTimeStyles indefinido.styles includes an undefined DateTimeStyles value.
- ou --or- NoCurrentDateDefault não é suportado.NoCurrentDateDefault is not supported.
- ou --or-
styles inclui valores DateTimeStyles mutuamente exclusivos.styles includes mutually exclusive DateTimeStyles values.
Exemplos
O exemplo a seguir chama o TryParse(String, IFormatProvider, DateTimeStyles, DateTimeOffset) método com uma variedade de DateTimeStyles valores para analisar algumas cadeias de caracteres com vários formatos de data e hora.The following example calls the TryParse(String, IFormatProvider, DateTimeStyles, DateTimeOffset) method with a variety of DateTimeStyles values to parse some strings with various date and time formats.
string dateString;
DateTimeOffset parsedDate;
dateString = "05/01/2008 6:00:00";
// Assume time is local
if (DateTimeOffset.TryParse(dateString, null as IFormatProvider,
DateTimeStyles.AssumeLocal,
out parsedDate))
Console.WriteLine("'{0}' was converted to {1}.",
dateString, parsedDate.ToString());
else
Console.WriteLine("Unable to parse '{0}'.", dateString);
// Assume time is UTC
if (DateTimeOffset.TryParse(dateString, null as IFormatProvider,
DateTimeStyles.AssumeUniversal,
out parsedDate))
Console.WriteLine("'{0}' was converted to {1}.",
dateString, parsedDate.ToString());
else
Console.WriteLine("Unable to parse '{0}'.", dateString);
// Parse and convert to UTC
dateString = "05/01/2008 6:00:00AM +5:00";
if (DateTimeOffset.TryParse(dateString, null as IFormatProvider,
DateTimeStyles.AdjustToUniversal,
out parsedDate))
Console.WriteLine("'{0}' was converted to {1}.",
dateString, parsedDate.ToString());
else
Console.WriteLine("Unable to parse '{0}'.", dateString);
// The example displays the following output to the console:
// '05/01/2008 6:00:00' was converted to 5/1/2008 6:00:00 AM -07:00.
// '05/01/2008 6:00:00' was converted to 5/1/2008 6:00:00 AM +00:00.
// '05/01/2008 6:00:00AM +5:00' was converted to 5/1/2008 1:00:00 AM +00:00.
Dim dateString As String
Dim parsedDate As DateTimeOffset
dateString = "05/01/2008 6:00:00"
' Assume time is local
If DateTimeOffset.TryParse(dateString, Nothing, _
DateTimeStyles.AssumeLocal, _
parsedDate) Then
Console.WriteLine("'{0}' was converted to {1}.", _
dateString, parsedDate.ToString())
Else
Console.WriteLine("Unable to parse '{0}'.", dateString)
End If
' Assume time is UTC
If DateTimeOffset.TryParse(dateString, Nothing, _
DateTimeStyles.AssumeUniversal, _
parsedDate) Then
Console.WriteLine("'{0}' was converted to {1}.", _
dateString, parsedDate.ToString())
Else
Console.WriteLine("Unable to parse '{0}'.", dateString)
End If
' Parse and convert to UTC
dateString = "05/01/2008 6:00:00AM +5:00"
If DateTimeOffset.TryParse(dateString, Nothing, _
DateTimeStyles.AdjustToUniversal, _
parsedDate) Then
Console.WriteLine("'{0}' was converted to {1}.", _
dateString, parsedDate.ToString())
Else
Console.WriteLine("Unable to parse '{0}'.", dateString)
End If
' The example displays the following output to the console:
' '05/01/2008 6:00:00' was converted to 5/1/2008 6:00:00 AM -07:00.
' '05/01/2008 6:00:00' was converted to 5/1/2008 6:00:00 AM +00:00.
' '05/01/2008 6:00:00AM +5:00' was converted to 5/1/2008 1:00:00 AM +00:00.
Comentários
Essa sobrecarga do TryParse(String, IFormatProvider, DateTimeStyles, DateTimeOffset) método é como o DateTimeOffset.Parse(String, IFormatProvider, DateTimeStyles) método, exceto que ele não lança uma exceção se a conversão falhar.This overload of the TryParse(String, IFormatProvider, DateTimeStyles, DateTimeOffset) method is like the DateTimeOffset.Parse(String, IFormatProvider, DateTimeStyles) method, except that it does not throw an exception if the conversion fails. O método analisa uma cadeia de caracteres com três elementos que podem aparecer em qualquer ordem e são delimitados por espaço em branco.The method parses a string with three elements that can appear in any order and are delimited by white space. Esses três elementos são mostrados na tabela a seguir.These three elements are shown in the following table.
| ElementoElement | ExemploExample |
|---|---|
| <Date> | "2/10/2007""2/10/2007" |
| <Time> | "1:02:03 PM""1:02:03 PM" |
| <Offset> | "-7:30""-7:30" |
Embora cada um desses elementos seja opcional, <Offset> não pode aparecer por si só.Although each of these elements is optional, <Offset> cannot appear by itself. Ele deve ser fornecido junto com o <Date> ou o <Time> .It must be provided together with either <Date> or <Time>. Se <Date> estiver ausente, seu valor padrão será o dia atual.If <Date> is missing, its default value is the current day. Se <Date> estiver presente, mas seu componente de ano consistir em apenas dois dígitos, ele será convertido em um ano no provider calendário atual do parâmetro com base no valor da Calendar.TwoDigitYearMax propriedade.If <Date> is present but its year component consists of only two digits, it is converted to a year in the provider parameter's current calendar based on the value of the Calendar.TwoDigitYearMax property. Se <Time> estiver ausente, seu valor padrão será 12:00:00 am.If <Time> is missing, its default value is 12:00:00 AM. Se <Offset> estiver ausente, seu valor padrão será o deslocamento do fuso horário local ou Zero se o DateTimeStyles.AdjustToUniversal DateTimeStyles.AssumeUniversal valor ou for especificado em styles .If <Offset> is missing, its default value is the offset of the local time zone, or Zero if either the DateTimeStyles.AdjustToUniversal or DateTimeStyles.AssumeUniversal value is specified in styles. Se <Offset> estiver presente, ele poderá representar um deslocamento negativo ou positivo do UTC (tempo Universal Coordenado).If <Offset> is present, it can represent either a negative or a positive offset from Coordinated Universal Time (UTC). Em ambos os casos, <Offset> deve incluir um símbolo de sinal ou o método retorna false .In either case, <Offset> must include a sign symbol or the method returns false.
A input cadeia de caracteres é analisada usando as informações de formatação específicas de cultura em um DateTimeFormatInfo objeto fornecido pelo formatProvider parâmetro.The input string is parsed by using the culture-specific formatting information in a DateTimeFormatInfo object supplied by the formatProvider parameter. O parâmetro formatProvider pode ser qualquer um dos seguintes:The formatProvider parameter can be either of the following:
Um CultureInfo objeto que representa a cultura cuja formatação é usada no
input.A CultureInfo object that represents the culture whose formatting is used ininput. O DateTimeFormatInfo objeto retornado pela CultureInfo.DateTimeFormat propriedade define o formato usado noinput.The DateTimeFormatInfo object returned by the CultureInfo.DateTimeFormat property defines the format that is used ininput.Um objeto DateTimeFormatInfo que define o formato dos dados de data e hora.A DateTimeFormatInfo object that defines the format of date and time data.
Além disso, cada elemento pode ser delimitado por espaços em branco à esquerda ou à direita, e os <Date> <Time> componentes e podem incluir espaço em branco interno (como 6:00:00).In addition, each element can be delimited by leading or trailing white space, and the <Date> and <Time> components can include inner white space (such as 6: 00:00). Somente o <Offset> componente não pode incluir espaço em branco interno.Only the <Offset> component cannot include inner white space.
Caso provider seja null, o objeto CultureInfo que corresponde à cultura atual é usado.If provider is null, the CultureInfo object that corresponds to the current culture is used.
O sinal positivo ou negativo usado em <Offset> deve ser + ou-.The positive or negative sign used in <Offset> must be either + or -. Ele não é definido pelas PositiveSign Propriedades ou NegativeSign do NumberFormatInfo objeto retornado pela formatprovider Propriedade do parâmetro NumberFormat .It is not defined by the PositiveSign or NegativeSign properties of the NumberFormatInfo object returned by the formatprovider parameter's NumberFormat property.
Há suporte para os seguintes membros da DateTimeStyles enumeração:The following members of the DateTimeStyles enumeration are supported:
| Membro DateTimeStylesDateTimeStyles Member | ComentáriosComments |
|---|---|
| AdjustToUniversal | Analisa a cadeia de caracteres representada por input e, se necessário, converte-a em UTC.Parses the string represented by input and, if necessary, converts it to UTC. É equivalente a analisar uma cadeia de caracteres e, em seguida, chamar o método do objeto retornado ToUniversalTime() .It is equivalent to parsing a string, and then calling the returned object's ToUniversalTime() method. |
| AllowInnerWhite | Embora válido, esse valor é ignorado.Although valid, this value is ignored. O espaço em branco interno é permitido <Date> nos <Time> componentes e.Inner white space is allowed in the <Date> and <Time> components. |
| AllowLeadingWhite | Embora válido, esse valor é ignorado.Although valid, this value is ignored. O espaço em branco à esquerda é permitido na frente de cada componente na cadeia de caracteres analisada.Leading white space is allowed in front of each component in the parsed string. |
| AllowTrailingWhite | Embora válido, esse valor é ignorado.Although valid, this value is ignored. O espaço em branco à direita é permitido na frente de cada componente na cadeia de caracteres analisada.Trailing white space is allowed in front of each component in the parsed string. |
| AllowWhiteSpaces | Esse é o comportamento padrão.This is the default behavior. Ele não pode ser substituído fornecendo um valor de enumeração mais restritivo DateTimeStyles , como DateTimeStyles.None .It cannot be overridden by supplying a more restrictive DateTimeStyles enumeration value, such as DateTimeStyles.None. |
| AssumeLocal | Indica que, se o input parâmetro não tem um <Offset> elemento, o deslocamento do fuso horário local deve ser fornecido.Indicates that, if the input parameter lacks an <Offset> element, the offset of the local time zone should be provided. Esse é o comportamento padrão do TryParse(String, IFormatProvider, DateTimeStyles, DateTimeOffset) método.This is the default behavior of the TryParse(String, IFormatProvider, DateTimeStyles, DateTimeOffset) method. |
| AssumeUniversal | Indica que, se o input parâmetro não tem um <Offset> elemento, o deslocamento UTC (00:00) deve ser fornecido.Indicates that, if the input parameter lacks an <Offset> element, the UTC offset (00:00) should be provided. |
| None | Embora seja válido, esse valor é ignorado e não tem efeito.Although valid, this value is ignored and has no effect. |
| RoundtripKind | Como a DateTimeOffset estrutura não inclui uma Kind propriedade, esse valor não tem nenhum efeito.Because the DateTimeOffset structure does not include a Kind property, this value has no effect. |
Somente o DateTimeStyles.NoCurrentDateDefault valor não tem suporte.Only the DateTimeStyles.NoCurrentDateDefault value is not supported. Um ArgumentException será gerado se esse valor for incluído no styles parâmetro.An ArgumentException is thrown if this value is included in the styles parameter.
Confira também
Aplica-se a
TryParse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles, DateTimeOffset)
Tenta converter a representação de intervalo especificada de uma data e hora em seu DateTimeOffset equivalente e retorna um valor que indica se a conversão foi bem-sucedida.Tries to convert a specified span representation of a date and time to its DateTimeOffset equivalent, and returns a value that indicates whether the conversion succeeded.
public:
static bool TryParse(ReadOnlySpan<char> input, IFormatProvider ^ formatProvider, System::Globalization::DateTimeStyles styles, [Runtime::InteropServices::Out] DateTimeOffset % result);
public static bool TryParse (ReadOnlySpan<char> input, IFormatProvider? formatProvider, System.Globalization.DateTimeStyles styles, out DateTimeOffset result);
public static bool TryParse (ReadOnlySpan<char> input, IFormatProvider formatProvider, System.Globalization.DateTimeStyles styles, out DateTimeOffset result);
static member TryParse : ReadOnlySpan<char> * IFormatProvider * System.Globalization.DateTimeStyles * DateTimeOffset -> bool
Public Shared Function TryParse (input As ReadOnlySpan(Of Char), formatProvider As IFormatProvider, styles As DateTimeStyles, ByRef result As DateTimeOffset) As Boolean
Parâmetros
- input
- ReadOnlySpan<Char>
Um intervalo que contém os caracteres que representam a data e a hora a serem convertidas.A span containing the characters representing the date and time to convert.
- formatProvider
- IFormatProvider
Um objeto que fornece informações de formatação específicas à cultura sobre input.An object that provides culture-specific formatting information about input.
- styles
- DateTimeStyles
Um combinação bit a bit de valores de enumeração que indica o formato permitido de input.A bitwise combination of enumeration values that indicates the permitted format of input.
- result
- DateTimeOffset
Quando é retornado, esse método contém o valor DateTimeOffset equivalente à data e hora de input, caso a conversão seja bem-sucedida ou MinValue caso a conversão falhe.When the method returns, contains the DateTimeOffset value equivalent to the date and time of input, if the conversion succeeded, or MinValue, if the conversion failed. A conversão falhará se o parâmetro input for null ou não contiver uma representação de cadeia de caracteres válida de uma data e hora.The conversion fails if the input parameter is null or does not contain a valid string representation of a date and time. Este parâmetro é passado não inicializado.This parameter is passed uninitialized.
Retornos
true caso o parâmetro input seja convertido com êxito; do contrário, false.true if the input parameter is successfully converted; otherwise, false.
Aplica-se a
TryParse(String, DateTimeOffset)
Tenta converter a representação de cadeia de caracteres especificada de uma data e hora em seu DateTimeOffset equivalente e retorna um valor que indica se a conversão foi bem-sucedida.Tries to converts a specified string representation of a date and time to its DateTimeOffset equivalent, and returns a value that indicates whether the conversion succeeded.
public:
static bool TryParse(System::String ^ input, [Runtime::InteropServices::Out] DateTimeOffset % result);
public static bool TryParse (string input, out DateTimeOffset result);
public static bool TryParse (string? input, out DateTimeOffset? result);
static member TryParse : string * DateTimeOffset -> bool
Public Shared Function TryParse (input As String, ByRef result As DateTimeOffset) As Boolean
Parâmetros
- input
- String
Uma cadeia de caracteres que contém uma data e hora a ser convertida.A string that contains a date and time to convert.
- result
- DateTimeOffset
Quando é retornado, esse método contém o DateTimeOffset equivalente à data e hora de input, caso a conversão seja bem-sucedida ou MinValue caso a conversão falhe.When the method returns, contains the DateTimeOffset equivalent to the date and time of input, if the conversion succeeded, or MinValue, if the conversion failed. A conversão falhará se o parâmetro input for null ou não contiver uma representação de cadeia de caracteres válida de uma data e hora.The conversion fails if the input parameter is null or does not contain a valid string representation of a date and time. Este parâmetro é passado não inicializado.This parameter is passed uninitialized.
Retornos
true caso o parâmetro input seja convertido com êxito; do contrário, false.true if the input parameter is successfully converted; otherwise, false.
Exemplos
O exemplo a seguir chama o TryParse(String, DateTimeOffset) método para analisar várias cadeias de caracteres com vários formatos de data e hora.The following example calls the TryParse(String, DateTimeOffset) method to parse several strings with various date and time formats.
DateTimeOffset parsedDate;
string dateString;
// String with date only
dateString = "05/01/2008";
if (DateTimeOffset.TryParse(dateString, out parsedDate))
Console.WriteLine("{0} was converted to {1}.",
dateString, parsedDate);
// String with time only
dateString = "11:36 PM";
if (DateTimeOffset.TryParse(dateString, out parsedDate))
Console.WriteLine("{0} was converted to {1}.",
dateString, parsedDate);
// String with date and offset
dateString = "05/01/2008 +7:00";
if (DateTimeOffset.TryParse(dateString, out parsedDate))
Console.WriteLine("{0} was converted to {1}.",
dateString, parsedDate);
// String with day abbreviation
dateString = "Thu May 01, 2008";
if (DateTimeOffset.TryParse(dateString, out parsedDate))
Console.WriteLine("{0} was converted to {1}.",
dateString, parsedDate);
// String with date, time with AM/PM designator, and offset
dateString = "5/1/2008 10:00 AM -07:00";
if (DateTimeOffset.TryParse(dateString, out parsedDate))
Console.WriteLine("{0} was converted to {1}.",
dateString, parsedDate);
// if (run on 3/29/07, the example displays the following output
// to the console:
// 05/01/2008 was converted to 5/1/2008 12:00:00 AM -07:00.
// 11:36 PM was converted to 3/29/2007 11:36:00 PM -07:00.
// 05/01/2008 +7:00 was converted to 5/1/2008 12:00:00 AM +07:00.
// Thu May 01, 2008 was converted to 5/1/2008 12:00:00 AM -07:00.
// 5/1/2008 10:00 AM -07:00 was converted to 5/1/2008 10:00:00 AM -07:00.
Dim parsedDate As DateTimeOffset
Dim dateString As String
' String with date only
dateString = "05/01/2008"
If DateTimeOffset.TryParse(dateString, parsedDate) Then _
Console.WriteLine("{0} was converted to {1}.", _
dateString, parsedDate)
' String with time only
dateString = "11:36 PM"
If DateTimeOffset.TryParse(dateString, parsedDate) Then _
Console.WriteLine("{0} was converted to {1}.", _
dateString, parsedDate)
' String with date and offset
dateString = "05/01/2008 +7:00"
If DateTimeOffset.TryParse(dateString, parsedDate) Then _
Console.WriteLine("{0} was converted to {1}.", _
dateString, parsedDate)
' String with day abbreviation
dateString = "Thu May 01, 2008"
If DateTimeOffset.TryParse(dateString, parsedDate) Then _
Console.WriteLine("{0} was converted to {1}.", _
dateString, parsedDate)
' String with date, time with AM/PM designator, and offset
dateString = "5/1/2008 10:00 AM -07:00"
If DateTimeOffset.TryParse(dateString, parsedDate) Then _
Console.WriteLine("{0} was converted to {1}.", _
dateString, parsedDate)
' If run on 3/29/07, the example displays the following output
' to the console:
' 05/01/2008 was converted to 5/1/2008 12:00:00 AM -07:00.
' 11:36 PM was converted to 3/29/2007 11:36:00 PM -07:00.
' 05/01/2008 +7:00 was converted to 5/1/2008 12:00:00 AM +07:00.
' Thu May 01, 2008 was converted to 5/1/2008 12:00:00 AM -07:00.
' 5/1/2008 10:00 AM -07:00 was converted to 5/1/2008 10:00:00 AM -07:00.
Comentários
Essa sobrecarga do TryParse(String, DateTimeOffset) método é como o DateTimeOffset.Parse(String) método, exceto que ele não lança uma exceção se a conversão falhar.This overload of the TryParse(String, DateTimeOffset) method is like the DateTimeOffset.Parse(String) method, except that it does not throw an exception if the conversion fails. Ele analisa uma cadeia de caracteres com três elementos que podem aparecer em qualquer ordem e são delimitados por espaço em branco.It parses a string with three elements that can appear in any order and are delimited by white space. Esses três elementos são mostrados na tabela a seguir.These three elements are shown in the following table.
| ElementoElement | ExemploExample |
|---|---|
| <Date> | "2/10/2007""2/10/2007" |
| <Time> | "1:02:03 PM""1:02:03 PM" |
| <Offset> | "-7:30""-7:30" |
Embora cada um desses elementos seja opcional, <Offset> não pode aparecer por si só.Although each of these elements is optional, <Offset> cannot appear by itself. Ele deve ser fornecido junto com o <Date> ou o <Time> .It must be provided together with either <Date> or <Time>. Se <Date> estiver ausente, seu valor padrão será o dia atual.If <Date> is missing, its default value is the current day. Se <Date> estiver presente, mas seu componente de ano consistir em apenas dois dígitos, ele será convertido em um ano no calendário atual da cultura atual com base no valor da Calendar.TwoDigitYearMax propriedade.If <Date> is present but its year component consists of only two digits, it is converted to a year in the current culture's current calendar based on the value of the Calendar.TwoDigitYearMax property. Se <Time> estiver ausente, seu valor padrão será 12:00:00 am.If <Time> is missing, its default value is 12:00:00 AM. Se <Offset> estiver ausente, seu valor padrão será o deslocamento do fuso horário local.If <Offset> is missing, its default value is the offset of the local time zone. Se <Offset> estiver presente, ele poderá representar um deslocamento negativo ou positivo do UTC (tempo Universal Coordenado).If <Offset> is present, it can represent either a negative or a positive offset from Coordinated Universal Time (UTC). Em ambos os casos, <Offset> deve incluir um símbolo de sinal ou o método retorna false .In either case, <Offset> must include a sign symbol or the method returns false.
A input cadeia de caracteres é analisada usando as informações de formatação em um DateTimeFormatInfo objeto inicializado para a cultura atual.The input string is parsed by using the formatting information in a DateTimeFormatInfo object initialized for the current culture. Para analisar uma cadeia de caracteres que contém a formatação designada que não corresponde necessariamente à da cultura atual, use o TryParseExact método e forneça um especificador de formato.To parse a string that contains designated formatting that does not necessarily correspond to that of the current culture, use the TryParseExact method and provide a format specifier.
Confira também
- Parse
- Amostra: Utilitário de Formatação do WinForms do .NET Core (C#)Sample: .NET Core WinForms Formatting Utility (C#)
- Amostra: Utilitário de Formatação do WinForms do .NET Core (Visual Basic)Sample: .NET Core WinForms Formatting Utility (Visual Basic)
Aplica-se a
TryParse(ReadOnlySpan<Char>, DateTimeOffset)
Tenta converter a representação de intervalo especificada de uma data e hora em seu DateTimeOffset equivalente e retorna um valor que indica se a conversão foi bem-sucedida.Tries to convert a specified span representation of a date and time to its DateTimeOffset equivalent, and returns a value that indicates whether the conversion succeeded.
public:
static bool TryParse(ReadOnlySpan<char> input, [Runtime::InteropServices::Out] DateTimeOffset % result);
public static bool TryParse (ReadOnlySpan<char> input, out DateTimeOffset result);
static member TryParse : ReadOnlySpan<char> * DateTimeOffset -> bool
Public Shared Function TryParse (input As ReadOnlySpan(Of Char), ByRef result As DateTimeOffset) As Boolean
Parâmetros
- input
- ReadOnlySpan<Char>
Um intervalo que contém os caracteres que representam a data e a hora a serem convertidas.A span containing the characters representing the date and time to convert.
- result
- DateTimeOffset
Quando é retornado, esse método contém o DateTimeOffset equivalente à data e hora de input, caso a conversão seja bem-sucedida ou MinValue caso a conversão falhe.When the method returns, contains the DateTimeOffset equivalent to the date and time of input, if the conversion succeeded, or MinValue, if the conversion failed. A conversão falhará se o parâmetro input for null ou não contiver uma representação de cadeia de caracteres válida de uma data e hora.The conversion fails if the input parameter is null or does not contain a valid string representation of a date and time. Este parâmetro é passado não inicializado.This parameter is passed uninitialized.
Retornos
true caso o parâmetro input seja convertido com êxito; do contrário, false.true if the input parameter is successfully converted; otherwise, false.