비고
이 문서는 이 API에 대한 참조 설명서를 보충하는 추가 설명을 제공합니다.
시간 객체 TimeSpan 는 양수 또는 음수 형태로 일, 시간, 분, 초 및 초의 부분 단위로 측정되는 시간 간격(지속 시간 또는 경과된 시간)을 나타냅니다. 이 구조체는 TimeSpan 특정 날짜와 관련이 없는 경우에만 하루 중 시간을 나타내는 데 사용할 수 있습니다. 그렇지 않으면 구조체 DateTime 를 DateTimeOffset 대신 사용해야 합니다. (구조를 사용하여 TimeSpan 하루 중 시간을 반영하는 방법에 대한 자세한 내용은 DateTime, DateTimeOffset, TimeSpan 및 TimeZoneInfo 중에서 선택 항목을 참조하세요.)
비고
값은 TimeSpan 시간 간격을 나타내며 특정 일 수, 시간, 분, 초 및 밀리초로 표현할 수 있습니다. 특정 시작점이나 끝점에 대한 참조 없이 일반적인 간격을 나타내므로 연도 및 월로 표현할 수 없으며 둘 다 일 수가 가변적입니다. DateTime 값은 특정 시간대를 참조하지 않는 날짜 및 시간을 나타내는 것과, DateTimeOffset 값은 특정 시간을 나타내는 것과 다릅니다.
구조에서 기간을 측정하는 데 사용하는 가장 큰 시간 TimeSpan 단위는 일입니다. 시간 간격은 월 및 연도와 같이 더 큰 시간 단위의 일 수가 다르기 때문에 일관성을 위해 일 단위로 측정됩니다.
개체의 TimeSpan 값은 표시된 시간 간격과 같은 틱 수입니다. 틱은 100나노초 또는 1초의 1,000만 분의 1과 같습니다. 개체의 값의 범위는 TimeSpan부터 TimeSpan.MinValue까지입니다.
TimeSpan 값 인스턴스화
다음과 같은 TimeSpan 여러 가지 방법으로 값을 인스턴스화할 수 있습니다.
암시적 매개 변수 없는 생성자를 호출합니다. 다음 예제와 같이 값이 TimeSpan.Zero있는 개체를 만듭니다.
TimeSpan interval = new TimeSpan(); Console.WriteLine(interval.Equals(TimeSpan.Zero)); // Displays "True".let interval = TimeSpan() printfn $"{interval.Equals TimeSpan.Zero}" // Displays "True".Dim interval As New TimeSpan() Console.WriteLine(interval.Equals(TimeSpan.Zero)) ' Displays "True".명시적 생성자 중 하나를 호출합니다. 다음 예제에서는 지정된 시간, 분 및 초 수로 값을 초기화 TimeSpan 합니다.
TimeSpan interval = new TimeSpan(2, 14, 18); Console.WriteLine(interval.ToString()); // Displays "02:14:18".let interval = TimeSpan(2, 14, 18) printfn $"{interval}" // Displays "02:14:18".Dim interval As New TimeSpan(2, 14, 18) Console.WriteLine(interval.ToString()) ' Displays "02:14:18".메서드를 호출하거나 TimeSpan 값을 반환하는 작업을 수행하여. 예를 들어 다음 예제와 같이 두 날짜 값과 시간 값 사이의 간격을 나타내는 값을 인스턴스화 TimeSpan 할 수 있습니다.
DateTime departure = new DateTime(2010, 6, 12, 18, 32, 0); DateTime arrival = new DateTime(2010, 6, 13, 22, 47, 0); TimeSpan travelTime = arrival - departure; Console.WriteLine($"{arrival} - {departure} = {travelTime}"); // The example displays the following output: // 6/13/2010 10:47:00 PM - 6/12/2010 6:32:00 PM = 1.04:15:00let departure = DateTime(2010, 6, 12, 18, 32, 0) let arrival = DateTime(2010, 6, 13, 22, 47, 0) let travelTime = arrival - departure printfn $"{arrival} - {departure} = {travelTime}" // The example displays the following output: // 6/13/2010 10:47:00 PM - 6/12/2010 6:32:00 PM = 1.04:15:00Dim departure As DateTime = #06/12/2010 6:32PM# Dim arrival As DateTime = #06/13/2010 10:47PM# Dim travelTime As TimeSpan = arrival - departure Console.WriteLine("{0} - {1} = {2}", arrival, departure, travelTime) ' The example displays the following output: ' 6/13/2010 10:47:00 PM - 6/12/2010 6:32:00 PM = 1.04:15:00다음 예제와 TimeSpan 같이 이러한 방식으로 개체를 0 시간 값으로 초기화할 수도 있습니다.
Random rnd = new Random(); TimeSpan timeSpent = TimeSpan.Zero; timeSpent += GetTimeBeforeLunch(); timeSpent += GetTimeAfterLunch(); Console.WriteLine($"Total time: {timeSpent}"); TimeSpan GetTimeBeforeLunch() { return new TimeSpan(rnd.Next(3, 6), 0, 0); } TimeSpan GetTimeAfterLunch() { return new TimeSpan(rnd.Next(3, 6), 0, 0); } // The example displays output like the following: // Total time: 08:00:00open System let rnd = Random() let getTimeBeforeLunch () = TimeSpan(rnd.Next(3, 6), 0, 0) let getTimeAfterLunch() = TimeSpan(rnd.Next(3, 6), 0, 0) do let timeSpent = TimeSpan.Zero let timeSpent = timeSpent + getTimeBeforeLunch () let timeSpent = timeSpent + getTimeAfterLunch () printfn $"Total time: {timeSpent}" // The example displays output like the following: // Total time: 08:00:00Module Example Dim rnd As New Random() Public Sub Main() Dim timeSpent As TimeSpan = TimeSpan.Zero timeSpent += GetTimeBeforeLunch() timeSpent += GetTimeAfterLunch() Console.WriteLine("Total time: {0}", timeSpent) End Sub Private Function GetTimeBeforeLunch() As TimeSpan Return New TimeSpan(rnd.Next(3, 6), 0, 0) End Function Private Function GetTimeAfterLunch() As TimeSpan Return New TimeSpan(rnd.Next(3, 6), 0, 0) End Function End Module ' The example displays output like the following: ' Total time: 08:00:00TimeSpan값은 산술 연산자와 DateTime, DateTimeOffset, TimeSpan 구조체의 메서드에 의해 반환됩니다.
TimeSpan 값의 문자열 표현을 구문 분석하여. Parse 및 TryParse 메서드를 사용하여 시간 간격이 포함된 문자열을 TimeSpan 값으로 변환할 수 있습니다. 다음 예제에서는 메서드를 Parse 사용하여 문자열 배열을 값으로 TimeSpan 변환합니다.
string[] values = { "12", "31.", "5.8:32:16", "12:12:15.95", ".12"}; foreach (string value in values) { try { TimeSpan ts = TimeSpan.Parse(value); Console.WriteLine($"'{value}' --> {ts}"); } catch (FormatException) { Console.WriteLine($"Unable to parse '{value}'"); } catch (OverflowException) { Console.WriteLine($"'{value}' is outside the range of a TimeSpan."); } } // The example displays the following output: // '12' --> 12.00:00:00 // Unable to parse '31.' // '5.8:32:16' --> 5.08:32:16 // '12:12:15.95' --> 12:12:15.9500000 // Unable to parse '.12'let values = [| "12"; "31."; "5.8:32:16"; "12:12:15.95"; ".12" |] for value in values do try let ts = TimeSpan.Parse value printfn $"'{value}' --> {ts}" with | :? FormatException -> printfn $"Unable to parse '{value}'" | :? OverflowException -> printfn $"'{value}' is outside the range of a TimeSpan." // The example displays the following output: // '12' --> 12.00:00:00 // Unable to parse '31.' // '5.8:32:16' --> 5.08:32:16 // '12:12:15.95' --> 12:12:15.9500000 // Unable to parse '.12'Dim values() As String = {"12", "31.", "5.8:32:16", "12:12:15.95", ".12"} For Each value As String In values Try Dim ts As TimeSpan = TimeSpan.Parse(value) Console.WriteLine("'{0}' --> {1}", value, ts) Catch e As FormatException Console.WriteLine("Unable to parse '{0}'", value) Catch e As OverflowException Console.WriteLine("'{0}' is outside the range of a TimeSpan.", value) End Try Next ' The example displays the following output: ' '12' --> 12.00:00:00 ' Unable to parse '31.' ' '5.8:32:16' --> 5.08:32:16 ' '12:12:15.95' --> 12:12:15.9500000 ' Unable to parse '.12'또한, TimeSpan 또는 ParseExact 메서드를 호출하여 구문 분석하고 값으로 변환할 입력 문자열의 정확한 형식을 정의할 수 있습니다.
TimeSpan 값에 대한 작업 수행
Addition 및 Subtraction 연산자를 사용하거나 Add 및 Subtract 메서드를 호출하여 시간을 추가하거나 뺄 수 있습니다. 및 메서드를 호출CompareCompareTo하여 두 시간 기간을 비교할 수도 있습니다Equals. 이 TimeSpan 구조에는 시간 간격을 양수 값과 음수 값으로 변환하는 Duration 및 Negate 메서드가 포함됩니다.
값의 범위는 TimeSpan, MinValue 입니다.
TimeSpan 값 서식 지정
TimeSpan 값은 [-]d.hh:mm:ss.ff 형식으로 나타낼 수 있습니다. 여기서 선택적인 빼기 기호는 음수 시간 간격을 나타냅니다. d 구성 요소는 일, hh는 24시간제로 측정한 시간, mm는 분, ss는 초, ff는 초의 분수를 나타냅니다. 즉, 시간 간격은 하루 중 시간이 없는 양수 또는 음수 일 수 또는 하루 중 시간이 있는 일 수 또는 하루 중 시간만 있는 일 수로 구성됩니다.
.NET Framework 4부터는 TimeSpan 구조체가 ToString 메서드 오버로드를 통해 값을 문자열 표현으로 변환할 때, 문화권별 형식을 지원합니다 TimeSpan. 기본 TimeSpan.ToString() 메서드는 이전 버전의 .NET Framework에서 반환 값과 동일한 고정 형식을 사용하여 시간 간격을 반환합니다. TimeSpan.ToString(String) 오버로드를 사용하면 시간 간격의 문자열 표현을 정의하는 형식 문자열을 지정할 수 있습니다. TimeSpan.ToString(String, IFormatProvider) 오버로드를 사용하면 형식 문자열 및 해당 형식 규칙이 시간 간격의 문자열 표현을 만드는 데 사용되는 문화권을 지정할 수 있습니다. TimeSpan 는 표준 및 사용자 지정 형식 문자열을 모두 지원합니다. (자세한 내용은 표준 TimeSpan 형식 문자열 및사용자 지정 TimeSpan 형식 문자열을 참조하세요.) 그러나 표준 형식 문자열만 문화권을 구분합니다.
레거시 TimeSpan 서식 복원
경우에 따라 .NET Framework 3.5 및 이전 버전에서 값의 서식을 성공적으로 지정 TimeSpan 하는 코드가 .NET Framework 4에서 실패합니다. 이는 TimeSpan_LegacyFormatMode< 요소 메서드를> 호출하여 형식 문자열을 사용하여 값의 형식을 TimeSpan 지정하는 코드에서 가장 일반적입니다. 다음 예제는 .NET Framework 3.5 및 이전 버전에서는 TimeSpan 값의 서식을 성공적으로 지정하지만, .NET Framework 4 이상 버전에서는 예외를 발생시킵니다. 주의할 점은, .NET Framework 3.5 및 이전 버전에서는 지원되지 않는 형식 지정자를 사용하여 TimeSpan 값을 서식화하려고 시도하지만 무시된다는 것입니다.
ShowFormattingCode();
// Output from .NET Framework 3.5 and earlier versions:
// 12:30:45
// Output from .NET Framework 4:
// Invalid Format
Console.WriteLine("---");
ShowParsingCode();
// Output:
// 000000006 --> 6.00:00:00
void ShowFormattingCode()
{
TimeSpan interval = new TimeSpan(12, 30, 45);
string output;
try
{
output = String.Format("{0:r}", interval);
}
catch (FormatException)
{
output = "Invalid Format";
}
Console.WriteLine(output);
}
void ShowParsingCode()
{
string value = "000000006";
try
{
TimeSpan interval = TimeSpan.Parse(value);
Console.WriteLine($"{value} --> {interval}");
}
catch (FormatException)
{
Console.WriteLine($"{value}: Bad Format");
}
catch (OverflowException)
{
Console.WriteLine($"{value}: Overflow");
}
}
let showFormattingCode () =
let interval = TimeSpan(12, 30, 45)
try
$"{interval:r}"
with :? FormatException ->
"Invalid Format"
|> printfn "%s"
let showParsingCode () =
let value = "000000006"
try
let interval = TimeSpan.Parse value
printfn $"{value} --> {interval}"
with
| :? FormatException ->
printfn $"{value}: Bad Format"
| :? OverflowException ->
printfn $"{value}: Overflow"
showFormattingCode ()
// Output from .NET Framework 3.5 and earlier versions:
// 12:30:45
// Output from .NET Framework 4:
// Invalid Format
printfn "---"
showParsingCode ()
// Output:
// 000000006 --> 6.00:00:00
Dim interval As New TimeSpan(12, 30, 45)
Dim output As String
Try
output = String.Format("{0:r}", interval)
Catch e As FormatException
output = "Invalid Format"
End Try
Console.WriteLine(output)
' Output from .NET Framework 3.5 and earlier versions:
' 12:30:45
' Output from .NET Framework 4:
' Invalid Format
코드를 수정할 수 없는 경우 다음 방법 중 하나로 값의 TimeSpan 레거시 서식을 복원할 수 있습니다.
TimeSpan_LegacyFormatMode 요소가 포함된 구성 파일을 만듭니다<.> 이 요소의
enabled특성을true로 설정하면 애플리케이션별로 레거시 TimeSpan 서식이 복원됩니다.애플리케이션 도메인을 만들 때 "NetFx40_TimeSpanLegacyFormatMode" 호환성 스위치를 설정합니다. 이렇게 하면 애플리케이션 도메인별로 레거시 TimeSpan 서식을 지정할 수 있습니다. 다음 예제에서는 레거시 서식을 사용하는 애플리케이션 도메인을 TimeSpan 만듭니다.
using System; public class Example2 { public static void Main() { AppDomainSetup appSetup = new AppDomainSetup(); appSetup.SetCompatibilitySwitches(new string[] { "NetFx40_TimeSpanLegacyFormatMode" }); AppDomain legacyDomain = AppDomain.CreateDomain("legacyDomain", null, appSetup); legacyDomain.ExecuteAssembly("ShowTimeSpan.exe"); } }open System let appSetup = AppDomainSetup() appSetup.SetCompatibilitySwitches [| "NetFx40_TimeSpanLegacyFormatMode" |] let legacyDomain = AppDomain.CreateDomain("legacyDomain", null, appSetup) legacyDomain.ExecuteAssembly "ShowTimeSpan.exe" |> ignoreModule Example3 Public Sub Main() Dim appSetup As New AppDomainSetup() appSetup.SetCompatibilitySwitches({"NetFx40_TimeSpanLegacyFormatMode"}) Dim legacyDomain As AppDomain = AppDomain.CreateDomain("legacyDomain", Nothing, appSetup) legacyDomain.ExecuteAssembly("ShowTimeSpan.exe") End Sub End Module다음 코드가 새 애플리케이션 도메인에서 실행되면 레거시 TimeSpan 서식 지정 동작으로 되돌아갑니다.
using System; public class Example3 { public static void Main() { TimeSpan interval = DateTime.Now - DateTime.Now.Date; string msg = String.Format("Elapsed Time Today: {0:d} hours.", interval); Console.WriteLine(msg); } } // The example displays the following output: // Elapsed Time Today: 01:40:52.2524662 hours.open System let interval = DateTime.Now - DateTime.Now.Date printfn $"Elapsed Time Today: {interval:d} hours." // The example displays the following output: // Elapsed Time Today: 01:40:52.2524662 hours.Module Example4 Public Sub Main() Dim interval As TimeSpan = Date.Now - Date.Now.Date Dim msg As String = String.Format("Elapsed Time Today: {0:d} hours.", interval) Console.WriteLine(msg) End Sub End Module ' The example displays output like the following: ' Elapsed Time Today: 01:40:52.2524662 hours.
.NET