5

Stripping Times from Dates in C#

 3 years ago
source link: https://www.stevefenton.co.uk/2021/08/stripping-times-from-dates-in-c/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Stripping Times from Dates in C#

This is a surprisingly common problem in C#, where you need to take a DateTime and strip off the “time” bit to leave you with a representation of a day. Currently, you can do it by creating a new DateTime and passing only the parts you want to keep, like year, month, and day.

DateTime expiryDateOnly =
    new DateTime(expiryDate.Year, expiryDate.Month, expiryDate.Day);

In .NET 6 we get an upgrade to this with some built in types. To solve our current case, we can use the DateOnly type, and there is an equivalent TimeOnly type too.

DateOnly expiryDateOnly =
    DateOnly.FromDateTime(expiryDate);

I’m looking forward to updating my date code to remove all the manual mapping to date-only dates!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK