How can I convert nullable DateTime to nullable DateOnly?
So DateTime? to DateOnly?
I can convert from DateTime to DateOnly by doing:
DateOnly mydate = DateOnly.FromDateTime(mydatetime);
but what about nullables?
I have a way but I don’t think is the best idea…
>Solution :
Let’s make an method that does exactly the same as FromDateTime, just invoked as an extension on DateTime:
public static DateOnly ToDateOnly(this DateTime datetime)
=> DateOnly.FromDateTime(datetime);
Now you can use the null-conditional member access operator ?. to lift this method to its nullable version:
var myNullableDateOnly = myNullableDateTime?.ToDateOnly();
Unfortunately, C# has no "null-conditional static method call operator". Thus, we need this "extension method workaround".