Como usar as estruturas DateOnly e TimeOnly
As estruturas DateOnly e TimeOnly foram introduzidas com o .NET 6 e representam uma data ou hora específica do dia, 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, desconsiderando a hora.
- 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 a hora. Como não tem nenhum componente de hora, ela representa uma data do início do dia até o final do dia. Essa estrutura é ideal para armazenar datas específicas, como uma data de nascimento, uma data de aniversário ou datas relacionadas a negócios.
Embora você possa usar DateTime
enquanto ignora o componente de hora, há alguns benefícios em usar DateOnly
em vez de DateTime
:
A estrutura
DateTime
poderá ser revertida para o dia anterior ou seguinte se for deslocada por um fuso horário.DateOnly
não pode ser deslocado por um fuso horário e sempre representa a data que foi definida.Serializar uma estrutura
DateTime
inclui o componente de hora, 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 a 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 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 DateOnly
de um DateTime
tipo, conforme demonstrado no seguinte código:
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
Três métodos são usados para ajustar uma DateOnly estrutura: AddDays, AddMonths e AddYears. Cada método usa um parâmetro inteiro e aumenta a data por essa medida. Se um número negativo for fornecido, a data será reduzida por essa medida. 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 de uma cadeia de caracteres, assim como a estrutura DateTime. Todos os tokens de análise baseados em data do .NET padrão funcionam com DateOnly
. Ao converter um tipo DateOnly
em uma cadeia de caracteres, você também pode usar padrões de formatação baseados em data do .NET. Para obter mais informações sobre cadeias de caracteres de formatação, confira 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 outras instâncias. Por exemplo, você pode marcar 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 em que você almoça todos os dias. TimeOnly
é limitado ao intervalo de 00:00:00.0000000 - 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 uma hora específica. No entanto, usar essas estruturas para simular uma hora sem uma 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 a movimentação para trás no tempo. UmTimeSpan
negativo não indica uma hora específica do dia.Se
TimeSpan
for usado como uma hora do dia, há o 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, adicionar 8 horas à estruturaTimeOnly
será revertido para 2:00Usar
DateTime
para uma hora do dia requer que uma data arbitrária seja associada à hora e, em seguida, seja desconsiderada. É uma prática comum escolherDateTime.MinValue
(0001-01-01) como a data; no entanto, se horas forem subtraídas do valorDateTime
, uma exceçãoOutOfRange
poderá ocorrer.TimeOnly
não tem esse problema, pois o tempo decorre para frente e para trás em torno do período de 24 horas.Serializar uma estrutura
DateTime
inclui o componente de data, que pode obscurecer a intenção dos dados. Além disso,TimeOnly
serializa menos dados.
Exemplos de TimeOnly
Use os seguintes exemplos para saber mais sobre TimeOnly
:
- Converter DateTime em TimeOnly
- Adicionar ou subtrair a hora
- 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 TimeOnly
de um DateTime
tipo, conforme demonstrado no seguinte código:
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 a hora
Três métodos são usados para ajustar uma TimeOnly estrutura: AddHours, AddMinutes e Add. AddHours
e AddMinutes
pegam um parâmetro inteiro e ajustam o valor adequadamente. Você pode usar um valor negativo para subtrair e um valor positivo para adicionar. Os métodos retornam uma nova instância de TimeOnly
, pois 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 reverte 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 1h30, adicione -4 horas a partir desse período e ele será revertido para 21:30:00
, que é 21h30. Há sobrecargas de método para AddHours
, AddMinutes
e Add
que capturam o número de dias revertidos.
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 de uma cadeia de caracteres, assim como a estrutura DateTime. Todos os tokens de análise baseados em hora do .NET padrão funcionam com TimeOnly
. Ao converter um tipo TimeOnly
em uma cadeia de caracteres, você também pode usar padrões de formatação baseados em data do .NET. Para obter mais informações sobre cadeias de caracteres de formatação, confira 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
dá suporte à serialização e desserialização dos 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, em seguida, desserializa-o novamente em uma nova instância do tipo Appointment
. Por fim, as instâncias originais e recém-desserializadas são comparadas quanto à 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 quanto à igualdade.
- O resultado da comparação é gravado no console.
Para obter mais informações, consulte Como serializar e desserializar o JSON no .NET.
Trabalhar com TimeSpan e DateTime
TimeOnly pode ser criado de e convertido em um TimeSpan. Além disso, TimeOnly
pode ser usado com um DateTime, seja para criar a instância TimeOnly
ou para criar uma instância DateTime
, desde que uma data seja fornecida.
O seguinte exemplo cria um objeto TimeOnly
de um TimeSpan
e 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 seguinte exemplo cria um DateTime
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 umas com as outras e você pode usar o método IsBetween para marcar se uma hora está entre duas outras horas. 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
Comentários
https://aka.ms/ContentUserFeedback.
Em breve: Ao longo de 2024, eliminaremos os problemas do GitHub como o mecanismo de comentários para conteúdo e o substituiremos por um novo sistema de comentários. Para obter mais informações, consulteEnviar e exibir comentários de