-1

In .NET 6 the DateOnly struct was introduced. How can one calculate the difference between two DateOnly structs (for example the total number of days)?

For two DateTime structs this can be done as follows:

    private int DaysDifferenceDateTime(DateTime dateTime1, DateTime dateTime2)
    {
        return (dateTime1 - dateTime2).Days;
    }

However if one tries this, it will not work:

    private int DaysDifferenceDateOnly(DateOnly dateOnly1, DateOnly dateOnly2)
    {
        return (dateOnly1 - dateOnly2).Days; // this is invalid code
    }

A possible workaround is to convert both DateOnly to DateTime:

    private int DaysDifferenceDateOnlyConverted(DateOnly dateOnly1, DateOnly dateOnly2)
    {
        return (new DateTime(dateOnly1.Year, dateOnly1.Month, dateOnly1.Day) - new DateTime(dateOnly2.Year, dateOnly2.Month, dateOnly2.Day)).Days;
    }

But is there a more elegant way to calculate the differences?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Bas de Raad
  • 556
  • 1
  • 6
  • 15

1 Answers1

4

I'm guessing the reason there's no implementation of the subtraction operator for that type is because there's no DateSpan type and a TimeSpan is a bit misleading.

What you can do is just to subtract the DayNumber from each other.

private int DaysDifferenceDateOnly(DateOnly dateOnly1, DateOnly dateOnly2)
{
    return dateOnly1.DayNumber - dateOnly2.DayNumber;
}
Xerillio
  • 4,855
  • 1
  • 17
  • 28