Come usare le strutture di DateOnly e TimeOnly
Le strutture di DateOnly e TimeOnly sono state introdotte con .NET 6 e rappresentano rispettivamente una data o un'ora specifiche. Prima di .NET 6 e sempre in .NET Framework, gli sviluppatori usavano il tipo DateTime (o un'altra alternativa) per rappresentare uno tra:
- Una data e un'ora complete.
- Una data, ignorando l'ora.
- Un'ora, ignorando la data.
DateOnly
e TimeOnly
sono tipi che rappresentano quelle parti specifiche di un tipo DateTime
.
Struttura di DateOnly
La struttura di DateOnly rappresenta una data specifica, senza l'ora. Poiché non ha il componente ora, rappresenta una data dall'inizio alla fine del giorno. Questa struttura è ideale per archiviare date specifiche, ad esempio una data di nascita, una data di anniversario o date correlate all'azienda.
Anche se è possibile usare DateTime
ignorando il componente ora, ci sono alcuni vantaggi nell'usare DateOnly
invece di DateTime
:
La struttura di
DateTime
può comprendere il giorno precedente o successivo se c'è una differenza in base a un fuso orario.DateOnly
non può essere scostata da un fuso orario e rappresenta sempre la data impostata.La serializzazione di una struttura
DateTime
include il componente ora, che può nascondere la finalità dei dati. Inoltre,DateOnly
serializza un numero inferiore di dati.Quando il codice interagisce con un database, ad esempio SQL Server, le date intere vengono in genere archiviate come tipo di dati
date
, che non includono un'ora.DateOnly
corrisponde al tipo di database migliore.
DateOnly
ha un intervallo compreso tra 0001-01-01 e 9999-12-31, proprio come DateTime
. È possibile specificare un calendario specifico nel costruttore DateOnly
. Tuttavia, un oggetto DateOnly
rappresenta sempre una data nel calendario gregoriano prolettico, indipendentemente dal calendario utilizzato per costruirlo. Ad esempio, è possibile compilare la data da un calendario ebraico, ma la data viene convertita in 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
Esempi di DateOnly
Usare gli esempi seguenti per informazioni su DateOnly
:
- Convertire DateTime in DateOnly
- Aggiungere o sottrarre giorni, mesi, anni
- Analizzare e formattare DateOnly
- Confrontare DateOnly
Convertire DateTime in DateOnly
Usare il metodo statico DateOnly.FromDateTime per creare un tipo DateOnly
da un tipo DateTime
, come illustrato nel codice seguente:
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
Aggiungere o sottrarre giorni, mesi, anni
Vengono usati tre metodi per regolare una struttura DateOnly: AddDays, AddMonths e AddYears. Ogni metodo accetta un parametro integer e aumenta la data in base a tale misurazione. Se viene specificato un numero negativo, la data viene ridotta di tale misura. I metodi restituiscono una nuova istanza di DateOnly
, perché la struttura non è modificabile.
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
Analizzare e formattare DateOnly
DateOnly può essere analizzato da una stringa, proprio come la struttura DateTime. Tutti i token di analisi standard .NET basati su data funzionano con DateOnly
. Quando si converte un tipo DateOnly
in una stringa, è possibile usare anche modelli di formattazione standard .NET. basati su data. Per altre informazioni sulla formattazione delle stringhe, vedere Stringhe di formato di data e ora standard.
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
Confrontare DateOnly
DateOnly può essere confrontato con altre istanze. Ad esempio, è possibile verificare se una data è precedente o successiva a un'altra data o se una data odierna corrisponde a una data specifica.
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
Struttura di TimeOnly
La struttura di TimeOnly rappresenta un valore dell'ora del giorno, ad esempio una sveglia quotidiana o l'ora in cui si pranza ogni giorno. TimeOnly
è limitato all'intervallo di 00:00:00.0000000 - 23:59:59.9999999, un'ora specifica del giorno.
Prima dell'introduzione del tipo TimeOnly
, i programmatori usavano in genere il tipo DateTime o il tipo TimeSpan per rappresentare un orario specifico. Tuttavia, l'uso di queste strutture per simulare un'ora senza una data può introdurre alcuni problemi, che TimeOnly
risolve:
TimeSpan
rappresenta il tempo trascorso, ad esempio il tempo misurato con un cronometro. L'intervallo superiore è superiore a 29.000 anni e il suo valore può essere negativo per indicare lo spostamento indietro nel tempo. UnTimeSpan
negativo non indica un'ora specifica del giorno.Se
TimeSpan
viene usato come ora del giorno, c'è il rischio che possa essere modificato in un valore che non rientra nel giorno di 24 ore.TimeOnly
non presenta questo rischio. Ad esempio, se il turno di lavoro di un dipendente inizia alle 18:00 e dura 8 ore, aggiungendo 8 ore alla strutturaTimeOnly
si passa a 02:00L'uso di
DateTime
per un'ora del giorno richiede che una data arbitraria sia associata all'ora e quindi ignorata in un secondo momento. È prassi comune scegliereDateTime.MinValue
(0001-01-01) come data, tuttavia, se le ore vengono sottratte dal valore diDateTime
, potrebbe verificarsi un'eccezioneOutOfRange
.TimeOnly
non presenta questo problema perché il tempo scorre avanti e indietro intorno all'intervallo di 24 ore.La serializzazione di una struttura
DateTime
include il componente data, che può nascondere la finalità dei dati. Inoltre,TimeOnly
serializza un numero inferiore di dati.
Esempi di TimeOnly
Usare gli esempi seguenti per informazioni su TimeOnly
:
- Convertire DateTime in TimeOnly
- Aggiungere o sottrarre il tempo
- Analizzare e formattare TimeOnly
- Usare TimeSpan e DateTime
- Operatori aritmetici e confronto di TimeOnly
Convertire DateTime in TimeOnly
Usare il metodo statico TimeOnly.FromDateTime per creare un tipo TimeOnly
da un tipo DateTime
, come illustrato nel codice seguente:
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
Aggiungere o sottrarre il tempo
Vengono usati tre metodi per regolare una struttura TimeOnly: AddHours, AddMinutes e Add. Sia AddHours
che AddMinutes
accettano un parametro Integer e regolano il valore di conseguenza. È possibile usare un valore negativo per sottrarre e un valore positivo per aggiungere. I metodi restituiscono una nuova istanza di TimeOnly
, perché la struttura non è modificabile. Il metodo Add
accetta un parametro TimeSpan e aggiunge o sottrae il valore dal valore TimeOnly
.
Poiché TimeOnly
rappresenta solo un periodo di 24 ore, si sposta in avanti o indietro di conseguenza quando si aggiungono i valori forniti a questi tre metodi. Ad esempio, se si usa un valore di 01:30:00
per rappresentare le 01:30, poi si aggiungono -4 ore a quel periodo, il valore si sposta indietro a 21:30:00
, ovvero alle 9:30 del pomeriggio. Esistono overload del metodo per AddHours
, AddMinutes
e Add
che acquisiscono il numero di giorni di cui è stato eseguito il roll over.
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
Analizzare e formattare TimeOnly
TimeOnly può essere analizzato da una stringa, proprio come la struttura DateTime. Tutti i token di analisi standard .NET basati sull'ora funzionano con TimeOnly
. Quando si converte un tipo TimeOnly
in una stringa, è possibile usare anche modelli di formattazione standard .NET. basati su data. Per altre informazioni sulla formattazione delle stringhe, vedere Stringhe di formato di data e ora standard.
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
Serializzare i tipi DateOnly e TimeOnly
Con .NET 7+, System.Text.Json
supporta la serializzazione e la deserializzazione dei tipi DateOnly e TimeOnly. Si consideri l'oggetto seguente:
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
L'esempio seguente serializza un oggetto Appointment
, visualizza il JSON risultante e successivamente lo deserializza nuovamente in una nuova istanza del tipo Appointment
. Infine, le istanze originali e appena deserializzate vengono confrontate per verificarne l'uguaglianza e i risultati vengono scritti nella 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}")
Nel codice precedente:
- Viene creata un'istanza di un oggetto
Appointment
e assegnata alla variabileappointment
. - L'istanza
appointment
viene serializzata in JSON usando JsonSerializer.Serialize. - Il JSON risultante viene scritto nella console.
- Il JSON viene deserializzato nuovamente in una nuova istanza del tipo
Appointment
usando JsonSerializer.Deserialize. - Le istanze originali e appena deserializzate vengono confrontate per verificarne l'uguaglianza.
- Il risultato del confronto viene scritto nella console.
Per altre informazioni, vedere Come serializzare e deserializzare dati JSON in .NET.
Usare TimeSpan e DateTime
TimeOnly può essere creato da e convertito in TimeSpan. Inoltre, TimeOnly
può essere usato con DateTime, per creare l'istanza TimeOnly
o per creare un'istanza DateTime
purché venga specificata una data.
L'esempio seguente crea un oggetto TimeOnly
da TimeSpan
e quindi lo converte di nuovo:
// 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
Nell'esempio seguente viene creato DateTime
da un oggetto TimeOnly
con una data arbitraria scelta:
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
Operatori aritmetici e confronto di TimeOnly
È possibile confrontare tra loro due istanze TimeOnly ed è possibile usare il metodo IsBetween per verificare se un orario si trova tra due altri orari. Quando viene utilizzato un operatore di addizione o sottrazione in TimeOnly
, viene restituito TimeSpan che rappresenta una durata di 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
Commenti e suggerimenti
https://aka.ms/ContentUserFeedback.
Presto disponibile: Nel corso del 2024 verranno gradualmente disattivati i problemi di GitHub come meccanismo di feedback per il contenuto e ciò verrà sostituito con un nuovo sistema di feedback. Per altre informazioni, vedereInvia e visualizza il feedback per