
Two new types have been introduced as part of the core library in .NET 6: DateOnly and TimeOnly. These types, which are structs (value types), allow developers to represent the part of either the date or the time of a DateTime and align well with how databases allow similar data to be represented.
Using DateOnly in .NET 6
The types should remain self-explanatory with regards to what they represent. Therefore we should use DateOnly when we need to represent a date without a time component. For instance, when representing the birthdate, the time portion of a DateTime is rarely needed. Using DateOnly, we can be more explicit about our intent.
It is possible to create an instance of DateOnly using the constructor taking the year, month and day as arguments:
var date = new DateOnly(1991, 07, 25);
PS: Internally, the DateOnly struct uses an integer to track a day number with a valid range of 0, mapped to 1st January 0001, to 3,652,058, mapped to 31st December 9999.
If you want to create a DateOnly instance from an existing DateTime, you can achieve this using the FromDateTime method:
var currentDate = DateOnly.FromDateTime(DateTime.Now.Utc);
As DateTime, we can also add days, months or years to a DateOnly instance, resulting in a new instance with the adjusted date:
var newDate = date.AddDays(1).AddMonths(1).AddYears(1);
Using TimeOnly in .NET 6
The TimeOnly struct allows to represent the time portion of the DateTime. This type is more convenient to use than DateTime when creating, for example, an alarm clock app that lets the user create a reoccurring alarm. In this case, the date is irrelevant.
The TimeOnly type has several constructor overloads. The more common ones are:
public TimeOnly(int hour, int minute);
public TimeOnly(int hour, int minute, int second);
public TimeOnly(int hour, int minute, int second, int millisecond);
PS: Internally, TimeOnly stores a long which represents the number of ticks (100 nanosecond intervals) that have elapsed since midnight by the defined time. For example, 1am is 1 hour into the day and therefore 36,000,000,000 ticks since midnight (00:00:00.0000000).
If you want to create a TimeOnly instance from an existing DateTime, you can do this using the FromDateTime method:
var currentTime = TimeOnly.FromDateTime(DateTime.Now.Utc);
We can perform mathematic operations with TimeOnly instances, such as calculating the difference:
var startTime = new TimeOnly(10, 30);
var endTime = new TimeOnly(17, 00, 00);
TimeSpan diff = endTime - startTime;
PS: The return type of this operation is a TimeSpan.