Search code examples
c#.netdatetime.net-6.0dateonly

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


Solution

  • public static DateOnly? ToNullableDateOnly(this DateTime? input) 
    {
        if (input == null) return null;
        return DateOnly.FromDateTime(input.Value);
    }