3

How can I convert nullable DateTime to nullable DateOnly? So 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...

Leandro Bardelli
  • 10,561
  • 15
  • 79
  • 116

4 Answers4

6

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

Heinzi
  • 167,459
  • 57
  • 363
  • 519
2

You can create a DateTime extension methods:

public static class DateTimeExtends
{
    public static DateOnly ToDateOnly(this DateTime date)
    {
        return new DateOnly(date.Year, date.Month, date.Day);
    }

    public static DateOnly? ToDateOnly(this DateTime? date)
    {
        return date != null ? (DateOnly?)date.Value.ToDateOnly() : null;
    }
}

And use on any DateTime instance:

DateOnly date = DateTime.Now.ToDateOnly();

NOTE: Not tested, maybe have a tipo error...

Victor
  • 2,313
  • 2
  • 5
  • 13
2
public static DateOnly? ToNullableDateOnly(this DateTime? input) 
{
    if (input == null) return null;
    return DateOnly.FromDateTime(input.Value);
}
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
0

I just create this method, if someone has another one better I'll glad to accept it as answer

    public DateOnly? NullableDateTime_To_NullableDateOnly(DateTime? input) {
        if (input != null)
        {
            return DateOnly.FromDateTime(input ?? DateTime.Now); //this is irrelevant but...
        }
        return null;
    }
Leandro Bardelli
  • 10,561
  • 15
  • 79
  • 116