Deconstructing A DateTime to Date and Time in C# & .NET
[C#, .NET]
Recently, I ran into a problem where I needed to extract the Date and Time components from a DateTime.
There are a couple of options around this.
Fetch The Values Directly From The DateTime
The first approach is perhaps the simplest. From the DateTime:
var now = DateTime.Now;
Console.WriteLine(now.Date);
Console.WriteLine(now.TimeOfDay);
Construct TimeOnly and DateOnly From The DateTime
In this approach, we use factory methods to construct the respective objects.
var now = DateTime.Now;
Console.WriteLine(DateOnly.FromDateTime(now));
Console.WriteLine(TimeOnly.FromDateTime(now));
Deconstruct The DateTime Into Its Constituents
Another method is to use the Deconstruct method of the DateTime to deconstruct it. Curiously, this method isn’t exposed to the IDE (EditorBrowsable), so you either have to know it is there or read the documentation to find it.
var now = DateTime.Now;
now.Deconstruct(out var date, out var time);
Console.WriteLine(date);
Console.WriteLine(time);
TLDR
There are a number of techniques to extract the Date and Time components from a given DateTime.