Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert nullable System.DateTime? to System.DateOnly?

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...

like image 744
Leandro Bardelli Avatar asked Dec 29 '25 00:12

Leandro Bardelli


1 Answers

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".

like image 137
Heinzi Avatar answered Dec 31 '25 13:12

Heinzi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!