DateTimeOffset.TryParse 方法

定义

将日期和时间的指定字符串表示形式转换为其等效的 DateTimeOffsetConverts a specified string representation of a date and time to its DateTimeOffset equivalent.

重载

TryParse(String, IFormatProvider, DateTimeStyles, DateTimeOffset)

尝试将日期和时间的指定字符串表示形式转换为其等效 DateTimeOffset,并返回一个指示转换是否成功的值。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)

尝试将日期和时间的指定范围表示形式转换为其等效 DateTimeOffset,并返回一个指示转换是否成功的值。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)

尝试将日期和时间的指定字符串表示形式转换为它的等效 DateTimeOffset,并返回一个指示转换是否成功的值。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)

尝试将日期和时间的指定范围表示形式转换为其等效 DateTimeOffset,并返回一个指示转换是否成功的值。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)

尝试将日期和时间的指定字符串表示形式转换为其等效 DateTimeOffset,并返回一个指示转换是否成功的值。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);
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

参数

input
String

包含要转换的日期和时间的字符串。A string that contains a date and time to convert.

formatProvider
IFormatProvider

一个对象,提供有关 input 的区域性特定格式设置信息。An object that provides culture-specific formatting information about input.

styles
DateTimeStyles

枚举值的一个按位组合,指示 input 所允许的格式。A bitwise combination of enumeration values that indicates the permitted format of input.

result
DateTimeOffset

当此方法返回时,如果转换成功,则包含与 DateTimeOffset 的日期和时间等效的 input;如果转换失败,则包含 MinValueWhen 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. 如果 input 参数为 null,或者不包含日期和时间的有效字符串表示形式,则转换失败。The conversion fails if the input parameter is null or does not contain a valid string representation of a date and time. 此参数在传递时尚未初始化。This parameter is passed uninitialized.

返回

如果 true 参数成功转换,则为 input;否则为 falsetrue if the input parameter is successfully converted; otherwise, false.

异常

styles 包括未定义的 DateTimeStyles 值。styles includes an undefined DateTimeStyles value.

-或--or- 不支持 NoCurrentDateDefaultNoCurrentDateDefault is not supported.

-或--or- styles 包括互斥的 DateTimeStyles 值。styles includes mutually exclusive DateTimeStyles values.

示例

下面的示例使用各种 DateTimeStyles 值调用 TryParse(String, IFormatProvider, DateTimeStyles, DateTimeOffset) 方法,以分析具有各种日期和时间格式的字符串。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.      

注解

TryParse(String, IFormatProvider, DateTimeStyles, DateTimeOffset) 方法的此重载与 DateTimeOffset.Parse(String, IFormatProvider, DateTimeStyles) 方法类似,不同之处在于,它不会在转换失败时引发异常。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. 方法分析一个字符串,其中包含三个元素,这些元素可按任意顺序出现并由空格分隔。The method parses a string with three elements that can appear in any order and are delimited by white space. 下表显示了这三个元素。These three elements are shown in the following table.

元素Element 示例Example
<日期 ><Date> "2/10/2007""2/10/2007"
<时间 ><Time> "1:02:03 PM""1:02:03 PM"
<偏移 ><Offset> "-7:30""-7:30"

尽管其中的每个元素都是可选的,但 > <偏移量不能单独出现。Although each of these elements is optional, <Offset> cannot appear by itself. 它必须与 <日期 > 或 <时间 > 一起提供。It must be provided together with either <Date> or <Time>. 如果缺少 <日期 >,则其默认值为当前日期。If <Date> is missing, its default value is the current day. 如果存在 <日期 > 但其年份组成部分只包含两个数字,则将根据 Calendar.TwoDigitYearMax 属性的值将其转换为 provider 参数的当前日历中的年份。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. 如果缺少 <时间 >,则其默认值为 12:00:00 AM。If <Time> is missing, its default value is 12:00:00 AM. 如果缺少 <Offset >,则其默认值为本地时区的偏移量,如果在 DateTimeStyles.AssumeUniversal 中指定了 DateTimeStyles.AdjustToUniversalstyles值,则为 ZeroIf <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. 如果存在 <Offset >,则它可以表示与协调世界时(UTC)之间的负值或正偏移量。If <Offset> is present, it can represent either a negative or a positive offset from Coordinated Universal Time (UTC). 在任一情况下,<偏移 > 必须包括符号符号或方法返回 falseIn either case, <Offset> must include a sign symbol or the method returns false.

input 字符串使用 formatProvider 参数提供的 DateTimeFormatInfo 对象中的区域性特定格式设置信息进行分析。The input string is parsed by using the culture-specific formatting information in a DateTimeFormatInfo object supplied by the formatProvider parameter. formatProvider 参数可以是以下项之一:The formatProvider parameter can be either of the following:

此外,每个元素可以用前导或尾随空格分隔,并且 <日期 > 和 <时间 > 组件可以包含内部空格(如 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). 仅 > 组件的 <偏移量不能包含内部空格。Only the <Offset> component cannot include inner white space.

如果 null``provider,则使用与当前区域性对应的 CultureInfo 对象。If provider is null, the CultureInfo object that corresponds to the current culture is used.

<Offset > 使用正号或负号,必须是 + 或-。The positive or negative sign used in <Offset> must be either + or -. 它不是由 formatprovider 参数的 NumberFormat 属性返回的 NumberFormatInfo 对象的 PositiveSignNegativeSign 属性来定义的。It is not defined by the PositiveSign or NegativeSign properties of the NumberFormatInfo object returned by the formatprovider parameter's NumberFormat property.

支持 DateTimeStyles 枚举的以下成员:The following members of the DateTimeStyles enumeration are supported:

DateTimeStyles 成员DateTimeStyles Member 注释Comments
AdjustToUniversal 分析由 input 表示的字符串,如有必要,将其转换为 UTC。Parses the string represented by input and, if necessary, converts it to UTC. 它等效于分析字符串,然后调用返回对象的 ToUniversalTime() 方法。It is equivalent to parsing a string, and then calling the returned object's ToUniversalTime() method.
AllowInnerWhite 虽然有效,但会忽略此值。Although valid, this value is ignored. <日期 > 和 <时间 > 组件允许内部空格。Inner white space is allowed in the <Date> and <Time> components.
AllowLeadingWhite 虽然有效,但会忽略此值。Although valid, this value is ignored. 分析字符串中的每个组件的前面都允许使用前导空格。Leading white space is allowed in front of each component in the parsed string.
AllowTrailingWhite 虽然有效,但会忽略此值。Although valid, this value is ignored. 分析字符串中的每个组件的前面都允许尾随空格。Trailing white space is allowed in front of each component in the parsed string.
AllowWhiteSpaces 此选项为默认行为。This is the default behavior. 不能通过提供限制性更强的 DateTimeStyles 枚举值(如 DateTimeStyles.None)来重写它。It cannot be overridden by supplying a more restrictive DateTimeStyles enumeration value, such as DateTimeStyles.None.
AssumeLocal 指示如果 input 参数缺少 <偏移量 > 元素,则应提供本地时区的偏移量。Indicates that, if the input parameter lacks an <Offset> element, the offset of the local time zone should be provided. 这是 TryParse(String, IFormatProvider, DateTimeStyles, DateTimeOffset) 方法的默认行为。This is the default behavior of the TryParse(String, IFormatProvider, DateTimeStyles, DateTimeOffset) method.
AssumeUniversal 指示如果 input 参数缺少 <偏移量 > 元素,则应提供 UTC 偏移量(00:00)。Indicates that, if the input parameter lacks an <Offset> element, the UTC offset (00:00) should be provided.
None 虽然有效,但此值将被忽略且不起作用。Although valid, this value is ignored and has no effect.
RoundtripKind 由于 DateTimeOffset 结构不包括 Kind 属性,因此此值无效。Because the DateTimeOffset structure does not include a Kind property, this value has no effect.

DateTimeStyles.NoCurrentDateDefault 值不受支持。Only the DateTimeStyles.NoCurrentDateDefault value is not supported. 如果 styles 参数中包含此值,则会引发 ArgumentExceptionAn ArgumentException is thrown if this value is included in the styles parameter.

另请参阅

TryParse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles, DateTimeOffset)

尝试将日期和时间的指定范围表示形式转换为其等效 DateTimeOffset,并返回一个指示转换是否成功的值。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);
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

参数

input
ReadOnlySpan<Char>

一个范围,包含表示要转换的日期和时间的字符。A span containing the characters representing the date and time to convert.

formatProvider
IFormatProvider

一个对象,提供有关 input 的区域性特定格式设置信息。An object that provides culture-specific formatting information about input.

styles
DateTimeStyles

枚举值的一个按位组合,指示 input 所允许的格式。A bitwise combination of enumeration values that indicates the permitted format of input.

result
DateTimeOffset

当此方法返回时,如果转换成功,则包含与 DateTimeOffset 的日期和时间等效的 input;如果转换失败,则包含 MinValueWhen 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. 如果 input 参数为 null,或者不包含日期和时间的有效字符串表示形式,则转换失败。The conversion fails if the input parameter is null or does not contain a valid string representation of a date and time. 此参数在传递时尚未初始化。This parameter is passed uninitialized.

返回

如果 true 参数成功转换,则为 input;否则为 falsetrue if the input parameter is successfully converted; otherwise, false.

TryParse(String, DateTimeOffset)

尝试将日期和时间的指定字符串表示形式转换为它的等效 DateTimeOffset,并返回一个指示转换是否成功的值。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);
static member TryParse : string * DateTimeOffset -> bool
Public Shared Function TryParse (input As String, ByRef result As DateTimeOffset) As Boolean

参数

input
String

包含要转换的日期和时间的字符串。A string that contains a date and time to convert.

result
DateTimeOffset

当此方法返回时,如果转换成功,则包含与 DateTimeOffset 的日期和时间等效的 input;如果转换失败,则包含 MinValueWhen the method returns, contains the DateTimeOffset equivalent to the date and time of input, if the conversion succeeded, or MinValue, if the conversion failed. 如果 input 参数为 null,或者不包含日期和时间的有效字符串表示形式,则转换失败。The conversion fails if the input parameter is null or does not contain a valid string representation of a date and time. 此参数在传递时尚未初始化。This parameter is passed uninitialized.

返回

如果 true 参数成功转换,则为 input;否则为 falsetrue if the input parameter is successfully converted; otherwise, false.

示例

下面的示例调用 TryParse(String, DateTimeOffset) 方法来分析多个具有各种日期和时间格式的字符串。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.                                 

注解

TryParse(String, DateTimeOffset) 方法的此重载与 DateTimeOffset.Parse(String) 方法类似,不同之处在于,它不会在转换失败时引发异常。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. 它分析一个字符串,其中包含三个元素,这些元素可按任意顺序出现并由空格分隔。It parses a string with three elements that can appear in any order and are delimited by white space. 下表显示了这三个元素。These three elements are shown in the following table.

元素Element 示例Example
<日期 ><Date> "2/10/2007""2/10/2007"
<时间 ><Time> "1:02:03 PM""1:02:03 PM"
<偏移 ><Offset> "-7:30""-7:30"

尽管其中的每个元素都是可选的,但 > <偏移量不能单独出现。Although each of these elements is optional, <Offset> cannot appear by itself. 它必须与 <日期 > 或 <时间 > 一起提供。It must be provided together with either <Date> or <Time>. 如果缺少 <日期 >,则其默认值为当前日期。If <Date> is missing, its default value is the current day. 如果存在 <日期 > 但其年份组成部分只包含两个数字,则将根据 Calendar.TwoDigitYearMax 属性的值将其转换为当前区域性当前日历中的年份。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. 如果缺少 <时间 >,则其默认值为 12:00:00 AM。If <Time> is missing, its default value is 12:00:00 AM. 如果缺少 <Offset >,则其默认值为本地时区的偏移量。If <Offset> is missing, its default value is the offset of the local time zone. 如果存在 <Offset >,则它可以表示与协调世界时(UTC)之间的负值或正偏移量。If <Offset> is present, it can represent either a negative or a positive offset from Coordinated Universal Time (UTC). 在任一情况下,<偏移 > 必须包括符号符号或方法返回 falseIn either case, <Offset> must include a sign symbol or the method returns false.

input 字符串使用为当前区域性初始化 DateTimeFormatInfo 对象中的格式设置信息进行分析。The input string is parsed by using the formatting information in a DateTimeFormatInfo object initialized for the current culture. 若要分析包含指定格式的字符串,该字符串不一定对应于当前区域性的指定格式设置,请使用 TryParseExact 方法并提供格式说明符。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.

另请参阅

TryParse(ReadOnlySpan<Char>, DateTimeOffset)

尝试将日期和时间的指定范围表示形式转换为其等效 DateTimeOffset,并返回一个指示转换是否成功的值。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

参数

input
ReadOnlySpan<Char>

一个范围,包含表示要转换的日期和时间的字符。A span containing the characters representing the date and time to convert.

result
DateTimeOffset

当此方法返回时,如果转换成功,则包含与 DateTimeOffset 的日期和时间等效的 input;如果转换失败,则包含 MinValueWhen the method returns, contains the DateTimeOffset equivalent to the date and time of input, if the conversion succeeded, or MinValue, if the conversion failed. 如果 input 参数为 null,或者不包含日期和时间的有效字符串表示形式,则转换失败。The conversion fails if the input parameter is null or does not contain a valid string representation of a date and time. 此参数在传递时尚未初始化。This parameter is passed uninitialized.

返回

如果 true 参数成功转换,则为 input;否则为 falsetrue if the input parameter is successfully converted; otherwise, false.

适用于