.NET 6 / C# 10 introduced TimeOnly and DateOnly structs, to represent only a time and only a date respectively.
The good old DateTime struct always had a Now static property which would give you the current date and time.
I was expecting both TimeOnly and DateOnly structs to have similar static properties; like TimeOnly.Now or DateOnly.Today, but they apparently don't.
So, what should I do if I want a DateOnly object representing the current date, or a TimeOnly object representing the current time?
And I would also like to know WHY they decided not to include properties like that on these two new structs?
The solution:
The way to create a
TimeOnlyorDateOnlyobject representing the current time or date would be to use theFromDateTimestatic method along withDateTime.Now. So like:If this is something you repeatedly need in your project, in order to avoid duplication, you could create extension methods on
DateTimeto convert aDateTimeinstance intoTimeOnlyorDateOnly:Usage:
Note that this would be not only useful for getting the current date or time as
TimeOnlyorDateOnly, but for converting any instance ofDateTimeintoTimeOnlyorDateOnly.Another approach would be to have two static classes like the following:
Usage:
Why isn't there a simple property on
DateOnlyandTimeOnly?The rationale behind why no
NoworTodayproperties were added to these structs was discussed here in this GitHub issue.In short, they didn't want to bring in timezones and everything into
DateOnlyandTimeOnlysince that would add extra complexity, so they decided against this, and kept the new structs simple and atomic.There is some discussion however about whether a property like that could be added to a
Clockclass (still a proposal, you can follow it here) so that the usage would be along the lines ofTimeOnly now = SystemClock.Local.Now, or forDateOnlylikeDateOnly today = SystemClock.Local.Todayor something like that. But that's still undecided.