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:

  1. Fetch the Date directly from the Date property
  2. Fetch the Time directly from the TimeOfDay property.
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

The other method is to use the Deconstruct method of the DateTime to deconstruct. Curiously, this method isn’t exposed to the IDE (EditorBrowsable) so you just have to know that it is there, or read the documentation to discover 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.