How can I convert DateTime? to DateOnly??
The error says:
Error CS0029 Cannot implicitly convert type 'System.DateOnly?' to 'System.DateTime?'
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...
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".
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