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

Time:05-05

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?

I have a way but I don't think is the best idea...

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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;
    }
  • Related