DateOnly 및 TimeOnly 구조를 사용하는 방법
DateOnly 및 TimeOnly 구조체는 .NET 6를 사용하여 도입되었으며 각각 특정 날짜 또는 시간을 나타냅니다. .NET 6 이전과 .NET Framework에서 항상 개발자는 DateTime 형식(또는 대체 형식)을 사용하여 다음 중 하나를 나타냈습니다.
- 전체 날짜 및 시간
- 날짜(시간 무시)
- 시간(날짜 무시)
DateOnly
및 TimeOnly
는 DateTime
형식의 특정 부분을 나타내는 형식입니다.
DateOnly 구조체
DateOnly 구조체는 시간 없는 특정 날짜를 나타냅니다. 시간 구성 요소가 없으므로 하루의 시작부터 종료까지의 날짜를 나타냅니다. 이 구조체는 생년월일, 기념일 또는 비즈니스 관련 날짜 등의 특정 날짜를 저장하는 데 적합합니다.
시간 구성 요소를 무시하면서 DateTime
을 사용할 수 있지만 DateOnly
를 사용할 경우 DateTime
보다 몇 가지 이점이 있습니다.
DateTime
구조체는 표준 시간대로 오프셋된 경우 이전 또는 다음 날로 롤링될 수 있습니다.DateOnly
는 표준 시간대로 오프셋할 수 없으며 항상 설정된 날짜를 나타냅니다.DateTime
구조체를 직렬화하면 데이터의 의도를 모호하게 할 수 있는 시간 구성 요소가 포함됩니다. 또한DateOnly
는 더 적은 데이터를 직렬화합니다.코드가 SQL Server와 같은 데이터베이스와 상호 작용하는 경우 전체 날짜는 일반적으로 시간을 포함하지 않는
date
데이터 형식으로 저장됩니다.DateOnly
는 데이터베이스 형식과 더 잘 일치합니다.
DateOnly
의 범위는 0001-01-01부터 9999-12-31까지입니다(예: DateTime
). DateOnly
생성자에서 특정 달력을 지정할 수 있습니다. 그러나 DateOnly
개체는 생성에 사용된 달력에 관계없이 항상 그레고리력의 날짜를 나타냅니다. 예를 들어 히브리어 달력에서 날짜를 작성할 수 있지만 날짜는 그레고리력으로 변환됩니다.
var hebrewCalendar = new System.Globalization.HebrewCalendar();
var theDate = new DateOnly(5776, 2, 8, hebrewCalendar); // 8 Cheshvan 5776
Console.WriteLine(theDate);
/* This example produces the following output:
*
* 10/21/2015
*/
Dim hebrewCalendar = New System.Globalization.HebrewCalendar()
Dim theDate = New DateOnly(5776, 2, 8, hebrewCalendar) ' 8 Cheshvan 5776
Console.WriteLine(theDate)
' This example produces the following output
'
' 10/21/2015
DateOnly 예제
다음 예제를 사용하여 DateOnly
에 대해 알아봅니다.
DateTime을 DateOnly로 변환
다음 코드에 설명된 대로 DateOnly.FromDateTime 정적 메서드를 사용하여 DateTime
형식에서 DateOnly
형식을 만듭니다.
var today = DateOnly.FromDateTime(DateTime.Now);
Console.WriteLine($"Today is {today}");
/* This example produces output similar to the following:
*
* Today is 12/28/2022
*/
Dim today = DateOnly.FromDateTime(DateTime.Now)
Console.WriteLine($"Today is {today}")
' This example produces output similar to the following
'
' Today is 12/28/2022
일, 월, 연도 추가 또는 빼기
DateOnly 구조체를 조정하는 데 사용되는 3가지 메서드는 AddDaysAddMonths 및 AddYears입니다. 각 메서드는 정수 매개 변수를 사용하고 해당 측정값에 따라 날짜를 늘립니다. 음수가 제공되면 해당 측정값에 따라 날짜가 줄어듭니다. 구조체는 변경 불가능하므로 메서드는 DateOnly
의 새 인스턴스를 반환합니다.
var theDate = new DateOnly(2015, 10, 21);
var nextDay = theDate.AddDays(1);
var previousDay = theDate.AddDays(-1);
var decadeLater = theDate.AddYears(10);
var lastMonth = theDate.AddMonths(-1);
Console.WriteLine($"Date: {theDate}");
Console.WriteLine($" Next day: {nextDay}");
Console.WriteLine($" Previous day: {previousDay}");
Console.WriteLine($" Decade later: {decadeLater}");
Console.WriteLine($" Last month: {lastMonth}");
/* This example produces the following output:
*
* Date: 10/21/2015
* Next day: 10/22/2015
* Previous day: 10/20/2015
* Decade later: 10/21/2025
* Last month: 9/21/2015
*/
Dim theDate = New DateOnly(2015, 10, 21)
Dim nextDay = theDate.AddDays(1)
Dim previousDay = theDate.AddDays(-1)
Dim decadeLater = theDate.AddYears(10)
Dim lastMonth = theDate.AddMonths(-1)
Console.WriteLine($"Date: {theDate}")
Console.WriteLine($" Next day: {nextDay}")
Console.WriteLine($" Previous day: {previousDay}")
Console.WriteLine($" Decade later: {decadeLater}")
Console.WriteLine($" Last month: {lastMonth}")
' This example produces the following output
'
' Date: 10/21/2015
' Next day: 10/22/2015
' Previous day: 10/20/2015
' Decade later: 10/21/2025
' Last month: 9/21/2015
DateOnly 구문 분석 및 서식 지정
DateOnly는 DateTime 구조체와 마찬가지로 문자열에서 구문 분석할 수 있습니다. 모든 표준 .NET 날짜 기반 구문 분석 토큰은 DateOnly
에서 작동합니다. DateOnly
형식을 문자열로 변환할 때 표준 .NET 날짜 기반 서식 지정 패턴도 사용할 수 있습니다. 문자열 서식 지정에 대한 자세한 내용은 표준 날짜 및 시간 형식 문자열을 참조하세요.
var theDate = DateOnly.ParseExact("21 Oct 2015", "dd MMM yyyy", CultureInfo.InvariantCulture); // Custom format
var theDate2 = DateOnly.Parse("October 21, 2015", CultureInfo.InvariantCulture);
Console.WriteLine(theDate.ToString("m", CultureInfo.InvariantCulture)); // Month day pattern
Console.WriteLine(theDate2.ToString("o", CultureInfo.InvariantCulture)); // ISO 8601 format
Console.WriteLine(theDate2.ToLongDateString());
/* This example produces the following output:
*
* October 21
* 2015-10-21
* Wednesday, October 21, 2015
*/
Dim theDate = DateOnly.ParseExact("21 Oct 2015", "dd MMM yyyy", CultureInfo.InvariantCulture) ' Custom format
Dim theDate2 = DateOnly.Parse("October 21, 2015", CultureInfo.InvariantCulture)
Console.WriteLine(theDate.ToString("m", CultureInfo.InvariantCulture)) ' Month day pattern
Console.WriteLine(theDate2.ToString("o", CultureInfo.InvariantCulture)) ' ISO 8601 format
Console.WriteLine(theDate2.ToLongDateString())
' This example produces the following output
'
' October 21
' 2015-10-21
' Wednesday, October 21, 2015
DateOnly 비교
DateOnly를 다른 인스턴스와 비교할 수 있습니다. 예를 들어 날짜가 다른 날짜 이전이거나 이후인지 또는 오늘 날짜가 특정 날짜와 일치하는지를 확인할 수 있습니다.
var theDate = DateOnly.ParseExact("21 Oct 2015", "dd MMM yyyy", CultureInfo.InvariantCulture); // Custom format
var theDate2 = DateOnly.Parse("October 21, 2015", CultureInfo.InvariantCulture);
var dateLater = theDate.AddMonths(6);
var dateBefore = theDate.AddDays(-10);
Console.WriteLine($"Consider {theDate}...");
Console.WriteLine($" Is '{nameof(theDate2)}' equal? {theDate == theDate2}");
Console.WriteLine($" Is {dateLater} after? {dateLater > theDate} ");
Console.WriteLine($" Is {dateLater} before? {dateLater < theDate} ");
Console.WriteLine($" Is {dateBefore} after? {dateBefore > theDate} ");
Console.WriteLine($" Is {dateBefore} before? {dateBefore < theDate} ");
/* This example produces the following output:
*
* Consider 10/21/2015
* Is 'theDate2' equal? True
* Is 4/21/2016 after? True
* Is 4/21/2016 before? False
* Is 10/11/2015 after? False
* Is 10/11/2015 before? True
*/
Dim theDate = DateOnly.ParseExact("21 Oct 2015", "dd MMM yyyy", CultureInfo.InvariantCulture) ' Custom format
Dim theDate2 = DateOnly.Parse("October 21, 2015", CultureInfo.InvariantCulture)
Dim dateLater = theDate.AddMonths(6)
Dim dateBefore = theDate.AddDays(-10)
Console.WriteLine($"Consider {theDate}...")
Console.WriteLine($" Is '{NameOf(theDate2)}' equal? {theDate = theDate2}")
Console.WriteLine($" Is {dateLater} after? {dateLater > theDate} ")
Console.WriteLine($" Is {dateLater} before? {dateLater < theDate} ")
Console.WriteLine($" Is {dateBefore} after? {dateBefore > theDate} ")
Console.WriteLine($" Is {dateBefore} before? {dateBefore < theDate} ")
' This example produces the following output
'
' Consider 10/21/2015
' Is 'theDate2' equal? True
' Is 4/21/2016 after? True
' Is 4/21/2016 before? False
' Is 10/11/2015 after? False
' Is 10/11/2015 before? True
TimeOnly 구조체
TimeOnly 구조체는 매일 알람 시계 또는 매일 점심을 먹는 시간과 같은 하루 중 시간 값을 나타냅니다. TimeOnly
는 특정 시간인 00:00:00.0000000 - 23:59:59.9999999 범위로 제한됩니다.
TimeOnly
형식이 도입되기 전에 프로그래머는 일반적으로 DateTime 형식 또는 TimeSpan 형식을 사용하여 특정 시간을 나타냈습니다. 그러나 이러한 구조체로 날짜가 없는 시간을 시뮬레이트하면 몇 가지 문제가 발생할 수 있으며 TimeOnly
에서 문제를 해결합니다.
TimeSpan
은 스톱워치로 측정된 시간과 같은 경과된 시간을 나타냅니다. 상한 범위는 29,000년 이상이며 해당 값은 시간상 뒤로 이동함을 나타내기 위해 음수일 수 있습니다. 음수TimeSpan
은 하루 중 특정 시간을 나타내지 않습니다.TimeSpan
을 하루 중 시간으로 사용하는 경우 24시간 외의 값으로 조작될 위험이 있습니다.TimeOnly
에는 이러한 위험이 없습니다. 예를 들어 직원의 교대 근무가 18:00에서 시작하여 8시간 동안 지속되는 경우TimeOnly
구조체에 8시간을 추가하여 2:00으로 롤오버됩니다.하루 중 시간에
DateTime
을 사용하려면 임의의 날짜를 시간과 연결한 후 나중에 무시해야 합니다.DateTime.MinValue
(0001-01-01)를 날짜로 선택하는 것이 일반적입니다. 그러나DateTime
값에서 시간을 빼면OutOfRange
예외가 발생할 수 있습니다. 시간이 24시간 범위로 앞뒤로 롤링되므로TimeOnly
에서 이 문제가 발생하지 않습니다.DateTime
구조체를 직렬화하면 날짜 구성 요소가 포함되며 이로 인해 데이터의 의도가 모호해질 수 있습니다. 또한TimeOnly
는 더 적은 데이터를 직렬화합니다.
TimeOnly 예제
다음 예제를 사용하여 TimeOnly
에 대해 알아봅니다.
- DateTime을 TimeOnly로 변환
- 시간 추가 또는 빼기
- TimeOnly 구문 분석 및 서식 지정
- TimeSpan 및 DateTime 작업
- 산술 연산자 및 TimeOnly 비교
DateTime을 TimeOnly로 변환
다음 코드에 설명된 대로 TimeOnly.FromDateTime 정적 메서드를 사용하여 DateTime
형식에서 TimeOnly
형식을 만듭니다.
var now = TimeOnly.FromDateTime(DateTime.Now);
Console.WriteLine($"It is {now} right now");
/* This example produces output similar to the following:
*
* It is 2:01 PM right now
*/
Dim now = TimeOnly.FromDateTime(DateTime.Now)
Console.WriteLine($"It is {now} right now")
' This example produces output similar to the following
'
' It is 2:01 PM right now
시간 추가 또는 빼기
TimeOnly 구조체를 조정하는 데 사용되는 3가지 메서드는 AddHoursAddMinutes 및 Add입니다. AddHours
및 AddMinutes
는 둘 다 정수 매개 변수를 사용하고 그에 따라 값을 조정합니다. 음수 값을 사용하여 빼거나 양수 값을 사용하여 추가할 수 있습니다. 구조체는 변경 불가능하므로 메서드는 TimeOnly
의 새 인스턴스를 반환합니다. Add
메서드는 TimeSpan 매개 변수를 사용하고 TimeOnly
값에서 값을 추가하거나 값을 뺍니다.
TimeOnly
는 24시간 기간을 나타내기 때문에 제공된 값을 이러한 세 가지 메서드에 추가할 때 적절하게 앞으로 또는 뒤로 롤오버됩니다. 예를 들어 01:30:00
값을 사용하여 오전 1시 30분을 나타내고 해당 기간부터 -4시간을 추가하면 오후 9시 30분에 해당하는 21:30:00
으로 롤백됩니다. 롤오버된 일 수를 캡처하는 AddHours
, AddMinutes
및 Add
에 대한 메서드 오버로드가 있습니다.
var theTime = new TimeOnly(7, 23, 11);
var hourLater = theTime.AddHours(1);
var minutesBefore = theTime.AddMinutes(-12);
var secondsAfter = theTime.Add(TimeSpan.FromSeconds(10));
var daysLater = theTime.Add(new TimeSpan(hours: 21, minutes: 200, seconds: 83), out int wrappedDays);
var daysBehind = theTime.AddHours(-222, out int wrappedDaysFromHours);
Console.WriteLine($"Time: {theTime}");
Console.WriteLine($" Hours later: {hourLater}");
Console.WriteLine($" Minutes before: {minutesBefore}");
Console.WriteLine($" Seconds after: {secondsAfter}");
Console.WriteLine($" {daysLater} is the time, which is {wrappedDays} days later");
Console.WriteLine($" {daysBehind} is the time, which is {wrappedDaysFromHours} days prior");
/* This example produces the following output:
*
* Time: 7:23 AM
* Hours later: 8:23 AM
* Minutes before: 7:11 AM
* Seconds after: 7:23 AM
* 7:44 AM is the time, which is 1 days later
* 1:23 AM is the time, which is -9 days prior
*/
Dim wrappedDays As Integer
Dim wrappedDaysFromHours As Integer
Dim theTime = New TimeOnly(7, 23, 11)
Dim hourLater = theTime.AddHours(1)
Dim minutesBefore = theTime.AddMinutes(-12)
Dim secondsAfter = theTime.Add(TimeSpan.FromSeconds(10))
Dim daysLater = theTime.Add(New TimeSpan(hours:=21, minutes:=200, seconds:=83), wrappedDays)
Dim daysBehind = theTime.AddHours(-222, wrappedDaysFromHours)
Console.WriteLine($"Time: {theTime}")
Console.WriteLine($" Hours later: {hourLater}")
Console.WriteLine($" Minutes before: {minutesBefore}")
Console.WriteLine($" Seconds after: {secondsAfter}")
Console.WriteLine($" {daysLater} is the time, which is {wrappedDays} days later")
Console.WriteLine($" {daysBehind} is the time, which is {wrappedDaysFromHours} days prior")
' This example produces the following output
'
' Time: 7:23 AM
' Hours later: 8:23 AM
' Minutes before: 7:11 AM
' Seconds after: 7:23 AM
' 7:44 AM is the time, which is 1 days later
' 1:23 AM is the time, which is -9 days prior
TimeOnly 구문 분석 및 서식 지정
TimeOnly는 DateTime 구조체와 마찬가지로 문자열에서 구문 분석할 수 있습니다. 모든 표준 .NET 시간 기반 구문 분석 토큰은 TimeOnly
에서 작동합니다. TimeOnly
형식을 문자열로 변환할 때 표준 .NET 날짜 기반 서식 지정 패턴도 사용할 수 있습니다. 문자열 서식 지정에 대한 자세한 내용은 표준 날짜 및 시간 형식 문자열을 참조하세요.
var theTime = TimeOnly.ParseExact("5:00 pm", "h:mm tt", CultureInfo.InvariantCulture); // Custom format
var theTime2 = TimeOnly.Parse("17:30:25", CultureInfo.InvariantCulture);
Console.WriteLine(theTime.ToString("o", CultureInfo.InvariantCulture)); // Round-trip pattern.
Console.WriteLine(theTime2.ToString("t", CultureInfo.InvariantCulture)); // Long time format
Console.WriteLine(theTime2.ToLongTimeString());
/* This example produces the following output:
*
* 17:00:00.0000000
* 17:30
* 5:30:25 PM
*/
Dim theTime = TimeOnly.ParseExact("5:00 pm", "h:mm tt", CultureInfo.InvariantCulture) ' Custom format
Dim theTime2 = TimeOnly.Parse("17:30:25", CultureInfo.InvariantCulture)
Console.WriteLine(theTime.ToString("o", CultureInfo.InvariantCulture)) ' Round-trip pattern.
Console.WriteLine(theTime2.ToString("t", CultureInfo.InvariantCulture)) ' Long time format
Console.WriteLine(theTime2.ToLongTimeString())
' This example produces the following output
'
' 17:00:00.0000000
' 17:30
' 5:30:25 PM
DateOnly 및 TimeOnly 형식 직렬화
.NET 7 이상에서 System.Text.Json
은 DateOnly 및 TimeOnly 형식을 직렬화 및 역직렬화할 수 있습니다. 다음 개체를 고려해 보세요.
sealed file record Appointment(
Guid Id,
string Description,
DateOnly Date,
TimeOnly StartTime,
TimeOnly EndTime);
Public NotInheritable Class Appointment
Public Property Id As Guid
Public Property Description As String
Public Property DateValue As DateOnly?
Public Property StartTime As TimeOnly?
Public Property EndTime As TimeOnly?
End Class
다음 예제에서는 Appointment
개체를 직렬화하고 결과 JSON을 표시한 다음, Appointment
형식의 새 인스턴스로 다시 역직렬화합니다. 마지막으로 원래 인스턴스와 새로 역직렬화된 인스턴스가 같은지 비교된 후 결과가 콘솔에 기록됩니다.
Appointment originalAppointment = new(
Id: Guid.NewGuid(),
Description: "Take dog to veterinarian.",
Date: new DateOnly(2002, 1, 13),
StartTime: new TimeOnly(5,15),
EndTime: new TimeOnly(5, 45));
string serialized = JsonSerializer.Serialize(originalAppointment);
Console.WriteLine($"Resulting JSON: {serialized}");
Appointment deserializedAppointment =
JsonSerializer.Deserialize<Appointment>(serialized)!;
bool valuesAreTheSame = originalAppointment == deserializedAppointment;
Console.WriteLine($"""
Original record has the same values as the deserialized record: {valuesAreTheSame}
""");
Dim originalAppointment As New Appointment With {
.Id = Guid.NewGuid(),
.Description = "Take dog to veterinarian.",
.DateValue = New DateOnly(2002, 1, 13),
.StartTime = New TimeOnly(5, 3, 1),
.EndTime = New TimeOnly(5, 3, 1)
}
Dim serialized As String = JsonSerializer.Serialize(originalAppointment)
Console.WriteLine($"Resulting JSON: {serialized}")
Dim deserializedAppointment As Appointment =
JsonSerializer.Deserialize(Of Appointment)(serialized)
Dim valuesAreTheSame As Boolean =
(originalAppointment.DateValue = deserializedAppointment.DateValue AndAlso
originalAppointment.StartTime = deserializedAppointment.StartTime AndAlso
originalAppointment.EndTime = deserializedAppointment.EndTime AndAlso
originalAppointment.Id = deserializedAppointment.Id AndAlso
originalAppointment.Description = deserializedAppointment.Description)
Console.WriteLine(
$"Original object has the same values as the deserialized object: {valuesAreTheSame}")
위의 코드에서
Appointment
개체가 인스턴스화되고appointment
변수에 할당됩니다.appointment
인스턴스가 JsonSerializer.Serialize를 사용하여 JSON으로 직렬화됩니다.- 결과 JSON이 콘솔에 기록됩니다.
- JSON은 JsonSerializer.Deserialize를 사용하여
Appointment
형식의 새 인스턴스로 다시 역직렬화됩니다. - 원래 인스턴스와 새로 역직렬화된 인스턴스가 같은지 비교됩니다.
- 비교 결과는 콘솔에 기록됩니다.
자세한 내용은 .NET에서 JSON을 직렬화 및 역직렬화하는 방법을 참조하세요.
TimeSpan 및 DateTime 작업
TimeSpan에서 TimeOnly를 만들고 거꾸로 변환할 수 있습니다. 또한 TimeOnly
를 DateTime과 함께 사용하여 TimeOnly
인스턴스를 만들거나 날짜가 제공되는 경우 DateTime
인스턴스를 만들 수 있습니다.
다음 예제에서는 TimeSpan
에서 TimeOnly
개체를 만든 다음, 다시 변환합니다.
// TimeSpan must in the range of 00:00:00.0000000 to 23:59:59.9999999
var theTime = TimeOnly.FromTimeSpan(new TimeSpan(23, 59, 59));
var theTimeSpan = theTime.ToTimeSpan();
Console.WriteLine($"Variable '{nameof(theTime)}' is {theTime}");
Console.WriteLine($"Variable '{nameof(theTimeSpan)}' is {theTimeSpan}");
/* This example produces the following output:
*
* Variable 'theTime' is 11:59 PM
* Variable 'theTimeSpan' is 23:59:59
*/
' TimeSpan must in the range of 00:00:00.0000000 to 23:59:59.9999999
Dim theTime = TimeOnly.FromTimeSpan(New TimeSpan(23, 59, 59))
Dim theTimeSpan = theTime.ToTimeSpan()
Console.WriteLine($"Variable '{NameOf(theTime)}' is {theTime}")
Console.WriteLine($"Variable '{NameOf(theTimeSpan)}' is {theTimeSpan}")
' This example produces the following output
'
' Variable 'theTime' is 11:59 PM
' Variable 'theTimeSpan' is 23:59:59
다음 예제에서는 임의의 날짜가 선택된 상태로 TimeOnly
개체에서 DateTime
을 만듭니다.
var theTime = new TimeOnly(11, 25, 46); // 11:25 AM and 46 seconds
var theDate = new DateOnly(2015, 10, 21); // October 21, 2015
var theDateTime = theDate.ToDateTime(theTime);
var reverseTime = TimeOnly.FromDateTime(theDateTime);
Console.WriteLine($"Date only is {theDate}");
Console.WriteLine($"Time only is {theTime}");
Console.WriteLine();
Console.WriteLine($"Combined to a DateTime type, the value is {theDateTime}");
Console.WriteLine($"Converted back from DateTime, the time is {reverseTime}");
/* This example produces the following output:
*
* Date only is 10/21/2015
* Time only is 11:25 AM
*
* Combined to a DateTime type, the value is 10/21/2015 11:25:46 AM
* Converted back from DateTime, the time is 11:25 AM
*/
Dim theTime = New TimeOnly(11, 25, 46) ' 11: 25 PM And 46 seconds
Dim theDate = New DateOnly(2015, 10, 21) ' October 21, 2015
Dim theDateTime = theDate.ToDateTime(theTime)
Dim reverseTime = TimeOnly.FromDateTime(theDateTime)
Console.WriteLine($"Date only is {theDate}")
Console.WriteLine($"Time only is {theTime}")
Console.WriteLine()
Console.WriteLine($"Combined to a DateTime type, the value is {theDateTime}")
Console.WriteLine($"Converted back from DateTime, the time is {reverseTime}")
' This example produces the following output
'
' Date only is 10/21/2015
' Time only is 11:25 AM
'
' Combined to a DateTime type, the value is 10/21/2015 11:25:46 AM
' Converted back from DateTime, the time is 11:25 AM
산술 연산자 및 TimeOnly 비교
두 TimeOnly 인스턴스를 서로 비교할 수 있으며 IsBetween 메서드를 사용하여 하나의 시간이 다른 두 시간 사이에 있는지 확인할 수 있습니다. TimeOnly
에서 더하기 또는 빼기 연산자를 사용하면 TimeSpan 시간이 반환되어 기간을 나타냅니다.
var start = new TimeOnly(10, 12, 01); // 10:12:01 AM
var end = new TimeOnly(14, 00, 53); // 02:00:53 PM
var outside = start.AddMinutes(-3);
var inside = start.AddMinutes(120);
Console.WriteLine($"Time starts at {start} and ends at {end}");
Console.WriteLine($" Is {outside} between the start and end? {outside.IsBetween(start, end)}");
Console.WriteLine($" Is {inside} between the start and end? {inside.IsBetween(start, end)}");
Console.WriteLine($" Is {start} less than {end}? {start < end}");
Console.WriteLine($" Is {start} greater than {end}? {start > end}");
Console.WriteLine($" Does {start} equal {end}? {start == end}");
Console.WriteLine($" The time between {start} and {end} is {end - start}");
/* This example produces the following output:
*
* Time starts at 10:12 AM and ends at 2:00 PM
* Is 10:09 AM between the start and end? False
* Is 12:12 PM between the start and end? True
* Is 10:12 AM less than 2:00 PM? True
* Is 10:12 AM greater than 2:00 PM? False
* Does 10:12 AM equal 2:00 PM? False
* The time between 10:12 AM and 2:00 PM is 03:48:52
*/
Dim startDate = New TimeOnly(10, 12, 1) ' 10:12:01 AM
Dim endDate = New TimeOnly(14, 0, 53) ' 02:00:53 PM
Dim outside = startDate.AddMinutes(-3)
Dim inside = startDate.AddMinutes(120)
Console.WriteLine($"Time starts at {startDate} and ends at {endDate}")
Console.WriteLine($" Is {outside} between the start and end? {outside.IsBetween(startDate, endDate)}")
Console.WriteLine($" Is {inside} between the start and end? {inside.IsBetween(startDate, endDate)}")
Console.WriteLine($" Is {startDate} less than {endDate}? {startDate < endDate}")
Console.WriteLine($" Is {startDate} greater than {endDate}? {startDate > endDate}")
Console.WriteLine($" Does {startDate} equal {endDate}? {startDate = endDate}")
Console.WriteLine($" The time between {startDate} and {endDate} is {endDate - startDate}")
' This example produces the following output
'
' Time starts at 10:12 AM And ends at 2:00 PM
' Is 10:09 AM between the start And end? False
' Is 12:12 PM between the start And end? True
' Is 10:12 AM less than 2:00 PM? True
' Is 10:12 AM greater than 2:00 PM? False
' Does 10:12 AM equal 2:00 PM? False
' The time between 10:12 AM and 2:00 PM is 03:48:52
.NET
피드백
https://aka.ms/ContentUserFeedback
출시 예정: 2024년 내내 콘텐츠에 대한 피드백 메커니즘으로 GitHub 문제를 단계적으로 폐지하고 이를 새로운 피드백 시스템으로 바꿀 예정입니다. 자세한 내용은 다음을 참조하세요.다음에 대한 사용자 의견 제출 및 보기