TimeSpan.TryParse 메서드
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
시간 간격에 대한 지정된 문자열 표현을 해당 TimeSpan으로 변환하고, 변환에 성공했는지 나타내는 값을 반환합니다.
오버로드
TryParse(ReadOnlySpan<Char>, TimeSpan) |
시간 간격에 대한 범위 표현을 해당 TimeSpan으로 변환하고, 변환에 성공했는지 나타내는 값을 반환합니다. |
TryParse(String, TimeSpan) |
시간 간격에 대한 문자열 표현을 해당 TimeSpan으로 변환하고, 변환에 성공했는지 여부를 나타내는 값을 반환합니다. |
TryParse(ReadOnlySpan<Char>, IFormatProvider, TimeSpan) |
지정된 문화권별 형식 정보를 사용하여 시간 간격에 대한 범위 표현을 해당 TimeSpan으로 변환하고, 변환에 성공했는지 나타내는 값을 반환합니다. |
TryParse(String, IFormatProvider, TimeSpan) |
지정된 문화권별 형식 정보를 사용하여 시간 간격에 대한 문자열 표현을 해당 TimeSpan으로 변환하고, 변환에 성공했는지 여부를 나타내는 값을 반환합니다. |
TryParse(ReadOnlySpan<Char>, TimeSpan)
- Source:
- TimeSpan.cs
- Source:
- TimeSpan.cs
- Source:
- TimeSpan.cs
시간 간격에 대한 범위 표현을 해당 TimeSpan으로 변환하고, 변환에 성공했는지 나타내는 값을 반환합니다.
public:
static bool TryParse(ReadOnlySpan<char> s, [Runtime::InteropServices::Out] TimeSpan % result);
public static bool TryParse (ReadOnlySpan<char> s, out TimeSpan result);
static member TryParse : ReadOnlySpan<char> * TimeSpan -> bool
Public Shared Function TryParse (s As ReadOnlySpan(Of Char), ByRef result As TimeSpan) As Boolean
매개 변수
- s
- ReadOnlySpan<Char>
변환할 시간 간격을 나타내는 문자를 포함하는 범위입니다.
- result
- TimeSpan
이 메서드가 반환될 때 s
에 지정된 시간 간격을 나타내는 개체를 포함하고, 변환이 실패할 경우에는 Zero를 포함합니다. 이 매개 변수는 초기화되지 않은 상태로 전달됩니다.
반환
s
이(가) 성공적으로 변환되었으면 true
이고, 그렇지 않으면 false
입니다. 이 작업은 매개 변수가 null
또는 이고Empty, 형식이 잘못되었거나, TimeSpan.MinValue보다 작거나 TimeSpan.MaxValue보다 크거나, 유효한 범위를 벗어난 최소 1일, 시간, 분 또는 초 구성 요소가 있는 시간 간격을 나타내는 경우 s
를 반환 false
합니다.
적용 대상
TryParse(String, TimeSpan)
- Source:
- TimeSpan.cs
- Source:
- TimeSpan.cs
- Source:
- TimeSpan.cs
시간 간격에 대한 문자열 표현을 해당 TimeSpan으로 변환하고, 변환에 성공했는지 여부를 나타내는 값을 반환합니다.
public:
static bool TryParse(System::String ^ s, [Runtime::InteropServices::Out] TimeSpan % result);
public static bool TryParse (string s, out TimeSpan result);
public static bool TryParse (string? s, out TimeSpan result);
static member TryParse : string * TimeSpan -> bool
Public Shared Function TryParse (s As String, ByRef result As TimeSpan) As Boolean
매개 변수
- s
- String
변환할 시간 간격을 지정하는 문자열입니다.
- result
- TimeSpan
이 메서드가 반환될 때 s
에 지정된 시간 간격을 나타내는 개체를 포함하고, 변환이 실패할 경우에는 Zero를 포함합니다. 이 매개 변수는 초기화되지 않은 상태로 전달됩니다.
반환
s
이(가) 성공적으로 변환되었으면 true
이고, 그렇지 않으면 false
입니다. 이 작업은 매개 변수가 null
또는 이고Empty, 형식이 잘못되었거나, TimeSpan.MinValue보다 작거나 TimeSpan.MaxValue보다 크거나, 유효한 범위를 벗어난 최소 1일, 시간, 분 또는 초 구성 요소가 있는 시간 간격을 나타내는 경우 s
를 반환 false
합니다.
예제
다음 예제에서는 메서드를 TryParse 사용하여 유효한 TimeSpan 문자열에서 개체를 만들고 TimeSpan 시간 범위 문자열이 잘못되어 구문 분석 작업이 실패한 시기를 나타냅니다.
using System;
public class TryParse
{
private static void ParseTimeSpan(string intervalStr)
{
// Write the first part of the output line.
Console.Write( "{0,20} ", intervalStr );
// Parse the parameter, and then convert it back to a string.
TimeSpan intervalVal;
if (TimeSpan.TryParse(intervalStr, out intervalVal))
{
string intervalToStr = intervalVal.ToString();
// Pad the end of the TimeSpan string with spaces if it
// does not contain milliseconds.
int pIndex = intervalToStr.IndexOf(':');
pIndex = intervalToStr.IndexOf('.', pIndex);
if (pIndex < 0)
intervalToStr += " ";
Console.WriteLine("{0,21}", intervalToStr);
// Handle failure of TryParse method.
}
else
{
Console.WriteLine("Parse operation failed.");
}
}
public static void Main()
{
Console.WriteLine( "{0,20} {1,21}",
"String to Parse", "TimeSpan" );
Console.WriteLine( "{0,20} {1,21}",
"---------------", "---------------------" );
ParseTimeSpan("0");
ParseTimeSpan("14");
ParseTimeSpan("1:2:3");
ParseTimeSpan("0:0:0.250");
ParseTimeSpan("10.20:30:40.50");
ParseTimeSpan("99.23:59:59.9999999");
ParseTimeSpan("0023:0059:0059.0099");
ParseTimeSpan("23:0:0");
ParseTimeSpan("24:0:0");
ParseTimeSpan("0:59:0");
ParseTimeSpan("0:60:0");
ParseTimeSpan("0:0:59");
ParseTimeSpan("0:0:60");
ParseTimeSpan("10:");
ParseTimeSpan("10:0");
ParseTimeSpan(":10");
ParseTimeSpan("0:10");
ParseTimeSpan("10:20:");
ParseTimeSpan("10:20:0");
ParseTimeSpan(".123");
ParseTimeSpan("0.12:00");
ParseTimeSpan("10.");
ParseTimeSpan("10.12");
ParseTimeSpan("10.12:00");
}
}
// String to Parse TimeSpan
// --------------- ---------------------
// 0 00:00:00
// 14 14.00:00:00
// 1:2:3 01:02:03
// 0:0:0.250 00:00:00.2500000
// 10.20:30:40.50 10.20:30:40.5000000
// 99.23:59:59.9999999 99.23:59:59.9999999
// 0023:0059:0059.0099 23:59:59.0099000
// 23:0:0 23:00:00
// 24:0:0 Parse operation failed.
// 0:59:0 00:59:00
// 0:60:0 Parse operation failed.
// 0:0:59 00:00:59
// 0:0:60 Parse operation failed.
// 10: Parse operation failed.
// 10:0 10:00:00
// :10 Parse operation failed.
// 0:10 00:10:00
// 10:20: Parse operation failed.
// 10:20:0 10:20:00
// .123 Parse operation failed.
// 0.12:00 12:00:00
// 10. Parse operation failed.
// 10.12 Parse operation failed.
// 10.12:00 10.12:00:00
open System
let parseTimeSpan intervalStr =
// Write the first part of the output line.
printf $"%20s{intervalStr} "
// Parse the parameter, and then convert it back to a string.
match TimeSpan.TryParse intervalStr with
| true, intervalVal ->
let intervalToStr = string intervalVal
// Pad the end of the TimeSpan string with spaces if it
// does not contain milliseconds.
let pIndex = intervalToStr.IndexOf ':'
let pIndex = intervalToStr.IndexOf('.', pIndex)
let intervalToStr =
if pIndex < 0 then
intervalToStr + " "
else intervalStr
printfn $"{intervalToStr,21}"
// Handle failure of TryParse method.
| _ ->
printfn "Parse operation failed."
printfn "%20s %21s" "String to Parse" "TimeSpan"
printfn "%20s %21s" "---------------" "---------------------"
parseTimeSpan "0"
parseTimeSpan "14"
parseTimeSpan "1:2:3"
parseTimeSpan "0:0:0.250"
parseTimeSpan "10.20:30:40.50"
parseTimeSpan "99.23:59:59.9999999"
parseTimeSpan "0023:0059:0059.0099"
parseTimeSpan "23:0:0"
parseTimeSpan "24:0:0"
parseTimeSpan "0:59:0"
parseTimeSpan "0:60:0"
parseTimeSpan "0:0:59"
parseTimeSpan "0:0:60"
parseTimeSpan "10:"
parseTimeSpan "10:0"
parseTimeSpan ":10"
parseTimeSpan "0:10"
parseTimeSpan "10:20:"
parseTimeSpan "10:20:0"
parseTimeSpan ".123"
parseTimeSpan "0.12:00"
parseTimeSpan "10."
parseTimeSpan "10.12"
parseTimeSpan "10.12:00"
// String to Parse TimeSpan
// --------------- ---------------------
// 0 00:00:00
// 14 14.00:00:00
// 1:2:3 01:02:03
// 0:0:0.250 00:00:00.2500000
// 10.20:30:40.50 10.20:30:40.5000000
// 99.23:59:59.9999999 99.23:59:59.9999999
// 0023:0059:0059.0099 23:59:59.0099000
// 23:0:0 23:00:00
// 24:0:0 Parse operation failed.
// 0:59:0 00:59:00
// 0:60:0 Parse operation failed.
// 0:0:59 00:00:59
// 0:0:60 Parse operation failed.
// 10: Parse operation failed.
// 10:0 10:00:00
// :10 Parse operation failed.
// 0:10 00:10:00
// 10:20: Parse operation failed.
// 10:20:0 10:20:00
// .123 Parse operation failed.
// 0.12:00 12:00:00
// 10. Parse operation failed.
// 10.12 Parse operation failed.
// 10.12:00 10.12:00:00
Module TryParse
Sub ParseTimeSpan( intervalStr As String )
' Write the first part of the output line.
Console.Write( "{0,20} ", intervalStr )
' Parse the parameter, and then convert it back to a string.
Dim intervalVal As TimeSpan
If TimeSpan.TryParse( intervalStr, intervalVal ) Then
Dim intervalToStr As String = intervalVal.ToString( )
' Pad the end of the TimeSpan string with spaces if it
' does not contain milliseconds.
Dim pIndex As Integer = intervalToStr.IndexOf( ":"c )
pIndex = intervalToStr.IndexOf( "."c, pIndex )
If pIndex < 0 Then intervalToStr &= " "
Console.WriteLine( "{0,21}", intervalToStr )
' Handle failure of TryParse method.
Else
Console.WriteLine("Parse operation failed.")
End If
End Sub
Public Sub Main( )
Console.WriteLine( "{0,20} {1,21}", _
"String to Parse", "TimeSpan" )
Console.WriteLine( "{0,20} {1,21}", _
"---------------", "---------------------" )
ParseTimeSpan("0")
ParseTimeSpan("14")
ParseTimeSpan("1:2:3")
ParseTimeSpan("0:0:0.250")
ParseTimeSpan("10.20:30:40.50")
ParseTimeSpan("99.23:59:59.9999999")
ParseTimeSpan("0023:0059:0059.0099")
ParseTimeSpan("23:0:0")
ParseTimeSpan("24:0:0")
ParseTimespan("0:59:0")
ParseTimeSpan("0:60:0")
ParseTimespan("0:0:59")
ParseTimeSpan("0:0:60")
ParseTimeSpan("10:")
ParsetimeSpan("10:0")
ParseTimeSpan(":10")
ParseTimeSpan("0:10")
ParseTimeSpan("10:20:")
ParseTimeSpan("10:20:0")
ParseTimeSpan(".123")
ParseTimeSpan("0.12:00")
ParseTimeSpan("10.")
ParseTimeSpan("10.12")
ParseTimeSpan("10.12:00")
End Sub
End Module
' This example generates the following output:
' String to Parse TimeSpan
' --------------- ---------------------
' 0 00:00:00
' 14 14.00:00:00
' 1:2:3 01:02:03
' 0:0:0.250 00:00:00.2500000
' 10.20:30:40.50 10.20:30:40.5000000
' 99.23:59:59.9999999 99.23:59:59.9999999
' 0023:0059:0059.0099 23:59:59.0099000
' 23:0:0 23:00:00
' 24:0:0 Parse operation failed.
' 0:59:0 00:59:00
' 0:60:0 Parse operation failed.
' 0:0:59 00:00:59
' 0:0:60 Parse operation failed.
' 10: Parse operation failed.
' 10:0 10:00:00
' :10 Parse operation failed.
' 0:10 00:10:00
' 10:20: Parse operation failed.
' 10:20:0 10:20:00
' .123 Parse operation failed.
' 0.12:00 12:00:00
' 10. Parse operation failed.
' 10.12 Parse operation failed.
' 10.12:00 10.12:00:00
설명
이 API에 대한 자세한 내용은 TimeSpan.TryParse에 대한 추가 API 설명을 참조하세요.
적용 대상
TryParse(ReadOnlySpan<Char>, IFormatProvider, TimeSpan)
- Source:
- TimeSpan.cs
- Source:
- TimeSpan.cs
- Source:
- TimeSpan.cs
지정된 문화권별 형식 정보를 사용하여 시간 간격에 대한 범위 표현을 해당 TimeSpan으로 변환하고, 변환에 성공했는지 나타내는 값을 반환합니다.
public:
static bool TryParse(ReadOnlySpan<char> input, IFormatProvider ^ formatProvider, [Runtime::InteropServices::Out] TimeSpan % result);
public:
static bool TryParse(ReadOnlySpan<char> input, IFormatProvider ^ formatProvider, [Runtime::InteropServices::Out] TimeSpan % result) = ISpanParsable<TimeSpan>::TryParse;
public static bool TryParse (ReadOnlySpan<char> input, IFormatProvider? formatProvider, out TimeSpan result);
public static bool TryParse (ReadOnlySpan<char> input, IFormatProvider formatProvider, out TimeSpan result);
static member TryParse : ReadOnlySpan<char> * IFormatProvider * TimeSpan -> bool
Public Shared Function TryParse (input As ReadOnlySpan(Of Char), formatProvider As IFormatProvider, ByRef result As TimeSpan) As Boolean
매개 변수
- input
- ReadOnlySpan<Char>
변환할 시간 간격을 나타내는 문자를 포함하는 범위입니다.
- formatProvider
- IFormatProvider
문화권별 형식 정보를 제공하는 개체입니다.
- result
- TimeSpan
이 메서드가 반환될 때 input
에 지정된 시간 간격을 나타내는 개체를 포함하고, 변환이 실패할 경우에는 Zero를 포함합니다. 이 매개 변수는 초기화되지 않은 상태로 전달됩니다.
반환
input
이(가) 성공적으로 변환되었으면 true
이고, 그렇지 않으면 false
입니다. 이 작업은 매개 변수가 null
또는 이고Empty, 형식이 잘못되었거나, TimeSpan.MinValue보다 작거나 TimeSpan.MaxValue보다 크거나, 유효한 범위를 벗어난 최소 1일, 시간, 분 또는 초 구성 요소가 있는 시간 간격을 나타내는 경우 input
를 반환 false
합니다.
적용 대상
TryParse(String, IFormatProvider, TimeSpan)
- Source:
- TimeSpan.cs
- Source:
- TimeSpan.cs
- Source:
- TimeSpan.cs
지정된 문화권별 형식 정보를 사용하여 시간 간격에 대한 문자열 표현을 해당 TimeSpan으로 변환하고, 변환에 성공했는지 여부를 나타내는 값을 반환합니다.
public:
static bool TryParse(System::String ^ input, IFormatProvider ^ formatProvider, [Runtime::InteropServices::Out] TimeSpan % result);
public:
static bool TryParse(System::String ^ input, IFormatProvider ^ formatProvider, [Runtime::InteropServices::Out] TimeSpan % result) = IParsable<TimeSpan>::TryParse;
public static bool TryParse (string input, IFormatProvider formatProvider, out TimeSpan result);
public static bool TryParse (string? input, IFormatProvider? formatProvider, out TimeSpan result);
static member TryParse : string * IFormatProvider * TimeSpan -> bool
Public Shared Function TryParse (input As String, formatProvider As IFormatProvider, ByRef result As TimeSpan) As Boolean
매개 변수
- input
- String
변환할 시간 간격을 지정하는 문자열입니다.
- formatProvider
- IFormatProvider
문화권별 형식 정보를 제공하는 개체입니다.
- result
- TimeSpan
이 메서드가 반환될 때 input
에 지정된 시간 간격을 나타내는 개체를 포함하고, 변환이 실패할 경우에는 Zero를 포함합니다. 이 매개 변수는 초기화되지 않은 상태로 전달됩니다.
반환
input
이(가) 성공적으로 변환되었으면 true
이고, 그렇지 않으면 false
입니다. 이 작업은 매개 변수가 null
또는 이고Empty, 형식이 잘못되었거나, TimeSpan.MinValue보다 작거나 TimeSpan.MaxValue보다 크거나, 유효한 범위를 벗어난 최소 1일, 시간, 분 또는 초 구성 요소가 있는 시간 간격을 나타내는 경우 input
를 반환 false
합니다.
예제
다음 예제에서는 개체의 CultureInfo 배열을 정의하고 메서드 호출에서 각 개체를 TryParse(String, IFormatProvider, TimeSpan) 사용하여 문자열 배열의 요소를 구문 분석합니다. 이 예제에서는 특정 문화권의 규칙이 서식 지정 작업에 미치는 영향을 보여 줍니다.
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
string[] values = { "6", "6:12", "6:12:14", "6:12:14:45",
"6.12:14:45", "6:12:14:45.3448",
"6:12:14:45,3448", "6:34:14:45" };
CultureInfo[] cultures = { new CultureInfo("en-US"),
new CultureInfo("ru-RU"),
CultureInfo.InvariantCulture };
string header = String.Format("{0,-17}", "String");
foreach (CultureInfo culture in cultures)
header += culture.Equals(CultureInfo.InvariantCulture) ?
String.Format("{0,20}", "Invariant") :
String.Format("{0,20}", culture.Name);
Console.WriteLine(header);
Console.WriteLine();
foreach (string value in values)
{
Console.Write("{0,-17}", value);
foreach (CultureInfo culture in cultures)
{
TimeSpan interval = new TimeSpan();
if (TimeSpan.TryParse(value, culture, out interval))
Console.Write("{0,20}", interval.ToString("c"));
else
Console.Write("{0,20}", "Unable to Parse");
}
Console.WriteLine();
}
}
}
// The example displays the following output:
// String en-US ru-RU Invariant
//
// 6 6.00:00:00 6.00:00:00 6.00:00:00
// 6:12 06:12:00 06:12:00 06:12:00
// 6:12:14 06:12:14 06:12:14 06:12:14
// 6:12:14:45 6.12:14:45 6.12:14:45 6.12:14:45
// 6.12:14:45 6.12:14:45 6.12:14:45 6.12:14:45
// 6:12:14:45.3448 6.12:14:45.3448000 Unable to Parse 6.12:14:45.3448000
// 6:12:14:45,3448 Unable to Parse 6.12:14:45.3448000 Unable to Parse
// 6:34:14:45 Unable to Parse Unable to Parse Unable to Parse
open System
open System.Globalization
let values =
[| "6"; "6:12"; "6:12:14"; "6:12:14:45"
"6.12:14:45"; "6:12:14:45.3448"
"6:12:14:45,3448"; "6:34:14:45" |]
let cultures =
[| CultureInfo "en-US"
CultureInfo "ru-RU"
CultureInfo.InvariantCulture |]
let mutable header = String.Format("{0,-17}", "String")
for culture in cultures do
header <-
if culture.Equals CultureInfo.InvariantCulture then
String.Format("{0,20}", "Invariant")
else
String.Format("{0,20}", culture.Name)
printfn $"{header}\n"
for value in values do
printf $"{value,-17}"
for culture in cultures do
match TimeSpan.TryParse(value, culture) with
| true, interval ->
printfn $"{interval,20:c}"
| _ ->
printfn "%20s" "Unable to Parse"
// The example displays the following output:
// String en-US ru-RU Invariant
//
// 6 6.00:00:00 6.00:00:00 6.00:00:00
// 6:12 06:12:00 06:12:00 06:12:00
// 6:12:14 06:12:14 06:12:14 06:12:14
// 6:12:14:45 6.12:14:45 6.12:14:45 6.12:14:45
// 6.12:14:45 6.12:14:45 6.12:14:45 6.12:14:45
// 6:12:14:45.3448 6.12:14:45.3448000 Unable to Parse 6.12:14:45.3448000
// 6:12:14:45,3448 Unable to Parse 6.12:14:45.3448000 Unable to Parse
// 6:34:14:45 Unable to Parse Unable to Parse Unable to Parse
Imports System.Globalization
Module Example
Public Sub Main()
Dim values() As String = { "6", "6:12", "6:12:14", "6:12:14:45",
"6.12:14:45", "6:12:14:45.3448",
"6:12:14:45,3448", "6:34:14:45" }
Dim cultures() As CultureInfo = { New CultureInfo("en-US"),
New CultureInfo("ru-RU"),
CultureInfo.InvariantCulture }
Dim header As String = String.Format("{0,-17}", "String")
For Each culture As CultureInfo In cultures
header += If(culture.Equals(CultureInfo.InvariantCulture),
String.Format("{0,20}", "Invariant"),
String.Format("{0,20}", culture.Name))
Next
Console.WriteLine(header)
Console.WriteLine()
For Each value As String In values
Console.Write("{0,-17}", value)
For Each culture As CultureInfo In cultures
Dim interval As New TimeSpan()
If TimeSpan.TryParse(value, culture, interval) Then
Console.Write("{0,20}", interval.ToString("c"))
Else
Console.Write("{0,20}", "Unable to Parse")
End If
Next
Console.WriteLine()
Next
End Sub
End Module
' The example displays the following output:
' String en-US ru-RU Invariant
'
' 6 6.00:00:00 6.00:00:00 6.00:00:00
' 6:12 06:12:00 06:12:00 06:12:00
' 6:12:14 06:12:14 06:12:14 06:12:14
' 6:12:14:45 6.12:14:45 6.12:14:45 6.12:14:45
' 6.12:14:45 6.12:14:45 6.12:14:45 6.12:14:45
' 6:12:14:45.3448 6.12:14:45.3448000 Unable to Parse 6.12:14:45.3448000
' 6:12:14:45,3448 Unable to Parse 6.12:14:45.3448000 Unable to Parse
' 6:34:14:45 Unable to Parse Unable to Parse Unable to Parse
설명
이 API에 대한 자세한 내용은 TimeSpan.TryParse에 대한 추가 API 설명을 참조하세요.
적용 대상
.NET
피드백
https://aka.ms/ContentUserFeedback
출시 예정: 2024년 내내 콘텐츠에 대한 피드백 메커니즘으로 GitHub 문제를 단계적으로 폐지하고 이를 새로운 피드백 시스템으로 바꿀 예정입니다. 자세한 내용은 다음을 참조하세요.다음에 대한 사용자 의견 제출 및 보기