Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What's the recommend way to implicitly convert type System.DateTime? to System.DateOnly?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading