'How to convert to and from DateTimeOffset and DateOnly?

I have a DateTimeOffset struct that i'd like to convert to and from DateOnly, but there seem to be no direct conversion options.

For DateTime there is FromDateTime(DateTime dateTime) - I do not see anything for DateTimeOffset.

How to convert to and from DateTimeOffset and DateOnly?



Solution 1:[1]

You could just used constructors:

DateOnly do1 = new (2022,03,14);
DateTimeOffset dto1 = new(do1.Year, do1.Month, do1.Day, 0, 0, 0, TimeSpan.FromHours(10));

and

DateTimeOffset dto2 = new(2022,03,14,23,40,11, TimeSpan.FromHours(10));
DateOnly do2 = new (dto2.Year, dto2.Month, dto2.Day);

Solution 2:[2]

You can just use .Date to get the date as a DateTime value, and FromDateTime to convert to DateOnly

DateOnly.FromDateTime(yourValue.Date)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tymtam
Solution 2 Charlieface