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

Calculate difference between two DateOnly structs (C#)

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:

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

    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?

>Solution :

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