How to convert to and from DateTimeOffset and DateOnly?

Viewed 1528

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?

2 Answers

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

DateOnly.FromDateTime(yourValue.Date)

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);
Related