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?
You can just use .Date to get the date as a DateTime value, and FromDateTime to convert to DateOnly
DateOnly.FromDateTime(yourValue.Date)
Note that the result of this is the date before taking the offset into account.
These existing answers very helpful and definitely got me looking in the right direction. What is missing from them is handling time zones. You may not care if all your dates are always in the same zone as your server. The following methods cover that use case.
Play with the code here: https://dotnetfiddle.net/kFOTd3
public static class DateOnlyExtensions {
public static DateTimeOffset ToDateTimeOffset(this DateOnly dateOnly, TimeZoneInfo zone) {
var dateTime = dateOnly.ToDateTime(new TimeOnly(0));
return new DateTimeOffset(dateTime, zone.GetUtcOffset(dateTime));
}
public static DateOnly ToDateOnly(this DateTimeOffset dto, TimeZoneInfo zone) {
var inTargetZone = TimeZoneInfo.ConvertTime(dto, zone);
return DateOnly.FromDateTime(inTargetZone.Date);
}
}
These can be used as follows:
public static void Main()
{
var now = DateTimeOffset.UtcNow;
var utc = TimeZoneInfo.Utc;
var hawaii = TimeZoneInfo.FindSystemTimeZoneById("Pacific/Honolulu");
var christmasIslands = TimeZoneInfo.FindSystemTimeZoneById("Pacific/Enderbury");
Console.WriteLine("DateTimeOffset to DateOnly:");
Console.WriteLine($"UTC Now: {now}");
Console.WriteLine($"Date in Hawaii: {now.ToDateOnly(hawaii)}");
Console.WriteLine($"Date In Christmas Islands: now.ToDateOnly(christmasIslands)}");
Console.WriteLine("====================\n");
Console.WriteLine("DateOnly to DateTimeOffset");
var totallyRandomDate = DateOnly.Parse("2020-03-11");
Console.WriteLine($"DateTimeOffset UTC: {totallyRandomDate.ToDateTimeOffset(utc)}");
Console.WriteLine($"DateTimeOffset Hawaii: {totallyRandomDate.ToDateTimeOffset(hawaii)}");
Console.WriteLine($"DateTimeOffset Christmas Islands: {totallyRandomDate.ToDateTimeOffset(christmasIslands)}");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With