Como usar as estruturas DateOnly e TimeOnly
As estruturas DateOnly e TimeOnly foram introduzidas com o .NET 6 e representam uma data ou hora do dia específica, respectivamente. Antes do .NET 6, e sempre no .NET Framework, os desenvolvedores usavam o tipo DateTime (ou alguma outra alternativa) para representar um dos seguintes:
- Uma data e hora inteiras.
- Uma data, sem considerar o tempo.
- Uma hora, desconsiderando a data.
DateOnly
e TimeOnly
são tipos que representam essas partes específicas de um tipo DateTime
.
A estrutura DateOnly
A estrutura DateOnly representa uma data específica, sem tempo. Uma vez que não tem componente de tempo, representa uma data desde o início do dia até ao final do dia. Essa estrutura é ideal para armazenar datas específicas, como uma data de nascimento, uma data de aniversário ou datas relacionadas ao negócio.
Embora você possa usar DateTime
ignorando o componente de tempo, há alguns benefícios em usar DateOnly
em vez de DateTime
:
A estrutura
DateTime
pode deslocar-se para o dia anterior ou seguinte se for ajustada por um fuso horário.DateOnly
não pode ser deslocado por um fuso horário e sempre representa a data que foi definida.A serialização de uma estrutura
DateTime
inclui o componente de tempo, que pode obscurecer a intenção dos dados. Além disso,DateOnly
serializa menos dados.Quando o código interage com um banco de dados, como o SQL Server, datas inteiras geralmente são armazenadas como o tipo de dados
date
, que não inclui uma hora.DateOnly
corresponde melhor ao tipo de banco de dados.
DateOnly
tem um intervalo de 0001-01-01 até 9999-12-31, assim como DateTime
. Você pode especificar um calendário específico no construtor DateOnly
. No entanto, um objeto DateOnly
sempre representa uma data no calendário gregoriano proléptico, independentemente de qual calendário foi usado para construí-lo. Por exemplo, você pode criar a data a partir de um calendário hebraico, mas a data é convertida em gregoriano:
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
Exemplos de DateOnly
Use os seguintes exemplos para saber mais sobre DateOnly
:
- Converter DateTime em DateOnly
- Adicionar ou subtrair dias, meses, anos
- Analisar e formatar DateOnly
- Comparar DateOnly
Converter DateTime em DateOnly
Use o método estático DateOnly.FromDateTime para criar um tipo de DateOnly
a partir de um tipo de DateTime
, conforme demonstrado no código a seguir:
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
Adicionar ou subtrair dias, meses, anos
Existem três métodos usados para ajustar uma estrutura DateOnly: AddDays, AddMonthse AddYears. Cada método usa um parâmetro inteiro e aumenta a data por essa medição. Se for fornecido um número negativo, a data é diminuída por essa medição. Os métodos retornam uma nova instância de DateOnly
, pois a estrutura é imutável.
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
Analisar e formatar DateOnly
DateOnly pode ser analisado a partir de uma cadeia de caracteres, assim como a estrutura DateTime. Todos os símbolos de análise padrão baseados em data do .NET funcionam com DateOnly
. Ao converter um tipo de DateOnly
em uma cadeia de caracteres, você também pode usar padrões de formatação padrão baseados em data do .NET. Para obter mais informações sobre como formatar cadeias de caracteres, consulte Cadeias de caracteres de formato de data e hora padrão.
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
Comparar "DateOnly"
DateOnly pode ser comparado com outros casos. Por exemplo, você pode verificar se uma data é antes ou depois de outra, ou se uma data hoje corresponde a uma data específica.
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
A estrutura TimeOnly
A estrutura TimeOnly representa um valor de hora do dia, como um despertador diário ou a hora que você almoça todos os dias.
TimeOnly
é limitado ao intervalo de 00:00:00.00000000 - 23:59:59.9999999, uma hora específica do dia.
Antes do tipo TimeOnly
ser introduzido, os programadores normalmente usavam o tipo DateTime ou o tipo TimeSpan para representar um tempo específico. No entanto, utilizar estas estruturas para simular uma hora sem data pode introduzir alguns problemas, o que TimeOnly
resolve:
TimeSpan
representa o tempo decorrido, como o tempo medido com um cronômetro. O intervalo superior é de mais de 29.000 anos, e seu valor pode ser negativo para indicar retrocesso no tempo. UmaTimeSpan
negativa não indica uma hora específica do dia.Se
TimeSpan
for usado como uma hora do dia, há um risco de que possa ser manipulado para um valor fora do dia de 24 horas.TimeOnly
não tem esse risco. Por exemplo, se o turno de trabalho de um funcionário começar às 18:00 e durar 8 horas, ao adicionar 8 horas à estruturaTimeOnly
, o horário avançará para as 2:00.Usar
DateTime
para uma hora do dia requer que uma data arbitrária seja associada à hora e, posteriormente, desconsiderada. É prática comum escolherDateTime.MinValue
(0001-01-01) como a data, no entanto, se as horas forem subtraídas do valorDateTime
, uma exceçãoOutOfRange
pode ocorrer.TimeOnly
não tem esse problema, pois o tempo rola para frente e para trás em torno do período de 24 horas.A serialização de uma estrutura de
DateTime
inclui o componente de data, que pode obscurecer a intenção dos dados. Além disso,TimeOnly
serializa menos dados.
Exemplos TimeOnly
Use os seguintes exemplos para saber mais sobre TimeOnly
:
- Converter DateTime para TimeOnly
- Adicionar ou subtrair tempo
- Analisar e formatar TimeOnly
- Trabalhar com TimeSpan e DateTime
- Operadores aritméticos e comparação de TimeOnly
Converter DateTime em TimeOnly
Use o método estático TimeOnly.FromDateTime para criar um tipo de TimeOnly
a partir de um tipo de DateTime
, conforme demonstrado no código a seguir:
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
Adicionar ou subtrair tempo
Existem três métodos usados para ajustar uma estrutura TimeOnly: AddHours, AddMinutese Add. Tanto AddHours
quanto AddMinutes
usam um parâmetro inteiro e ajustam o valor de acordo. Você pode usar um valor negativo para subtrair e um valor positivo para adicionar. Os métodos devolvem uma nova instância de TimeOnly
, já que a estrutura é imutável. O método Add
usa um parâmetro TimeSpan e adiciona ou subtrai o valor do valor TimeOnly
.
Como TimeOnly
representa apenas um período de 24 horas, ele rola para frente ou para trás adequadamente ao adicionar valores fornecidos a esses três métodos. Por exemplo, se você usar um valor de 01:30:00
para representar 1:30 AM, em seguida, adicionar -4 horas desse período, ele rola para trás para 21:30:00
, que é 21:30. Existem sobrecargas de método para AddHours
, AddMinutes
e Add
que capturam o número de dias acumulados.
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
Analisar e formatar TimeOnly
TimeOnly pode ser analisado a partir de uma cadeia de caracteres, assim como a estrutura DateTime. Todos os tokens de análise padrão baseados em tempo do .NET funcionam com TimeOnly
. Ao converter um tipo de TimeOnly
em uma cadeia de caracteres, você também pode usar padrões de formatação padrão baseados em data do .NET. Para obter mais informações sobre como formatar cadeias de caracteres, consulte Cadeias de caracteres de formato de data e hora padrão.
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
Serializar os tipos DateOnly e TimeOnly
Com o .NET 7+, o System.Text.Json
oferece suporte à serialização e desserialização de tipos DateOnly e TimeOnly. Considere o seguinte objeto:
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
O exemplo a seguir serializa um objeto Appointment
, exibe o JSON resultante e o desserializa novamente em uma nova instância do tipo Appointment
. Finalmente, as instâncias originais e recém-desserializadas são comparadas para igualdade e os resultados são gravados no console:
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}")
No código anterior:
- Um objeto
Appointment
é instanciado e atribuído à variávelappointment
. - A instância
appointment
é serializada para JSON usando JsonSerializer.Serialize. - O JSON resultante é gravado no console.
- O JSON é desserializado novamente em uma nova instância do tipo
Appointment
usando JsonSerializer.Deserialize. - As instâncias originais e recém-desserializadas são comparadas para verificar a igualdade.
- O resultado da comparação é gravado no console.
Para obter mais informações, consulte Como serializar e desserializar JSON no .NET.
Trabalhar com TimeSpan e DateTime
TimeOnly pode ser criado e convertido em TimeSpan. Além disso, TimeOnly
pode ser usado com um DateTime, para criar a instância TimeOnly
ou para criar uma instância DateTime
, desde que uma data seja fornecida.
O exemplo a seguir cria um objeto TimeOnly
a partir de um TimeSpan
e, em seguida, o converte novamente:
// 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
O exemplo a seguir cria um DateTime
a partir de um objeto TimeOnly
, com uma data arbitrária escolhida:
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
Operadores aritméticos e comparação de TimeOnly
Duas instâncias TimeOnly podem ser comparadas entre si, e você pode usar o método IsBetween para verificar se um tempo está entre dois outros tempos. Quando um operador de adição ou subtração é usado em um TimeOnly
, um TimeSpan é retornado, representando uma duração de tempo.
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