Updated on

To get the number of days between two dates in C#, we subtract one DateTime from the other and read the Days property of the TimeSpan we get back. For dates without a time, DateOnly.DayNumber gives the same count, and DateTimeOffset handles dates in different time zones.

The time of day and daylight saving time can each cost us a day, so we’ll look at both of them too.

To download the source code for this article, you can visit our GitHub repository.

Let’s start.

Understanding Date Handling in C#

Whether it’s booking a hotel room, checking flight schedules, or managing project timelines, there’s often a need to determine the duration between selected dates.

Date handling in C# is important because it enables us to work with dates and times efficiently. It allows us to perform calculations, comparisons, and manipulations with dates, which is essential for a wide range of applications.

Now that we understand the importance of date handling, let’s note that in this article we will use the Days property of the TimeSpan struct. However, it’s beneficial to be aware of another property called TotalDays. The key difference is that TotalDays provides the entire duration of the time interval in days as a double, including both full and partial days, while Days only counts complete 24-hour periods and therefore returns an int value.

That said, let’s take a look at some practical examples.

How Do We Get the Difference Between Two Dates in Days?

We subtract the earlier date from the later one and read the Days property of the result. Subtracting one DateTime from another gives us a TimeSpan, the type .NET uses for a length of time, and Days tells us how many whole days fit into it.

So (endDate - startDate).Days is the whole calculation. If the start date is later than the end date, we get a negative number, which tells us the date has already passed.

Days counts only complete 24-hour periods. When both values sit at midnight, that matches the calendar. When one of them carries a time of day, the count can come out a day short, and we’ll deal with that case in a moment.

For values that hold only a date, DateOnly takes a shorter route: endDate.DayNumber - startDate.DayNumber returns the count as an int without a TimeSpan in between.

Let’s try it on a real countdown.

Most of us can relate to the excitement of summer vacation, with some of us even counting down the days until the vacation finally begins.

Drawing from this shared experience, let’s see how we can calculate the number of days from today until the start of summer vacation:

var summerVacationStart = new DateTime(2024, 6, 1);
var currentDate = new DateTime(2024, 1, 13);

First, we define summerVacationStart as a DateTime struct, representing the start of summer vacation on June 1st, 2024. This is achieved by specifying the year, month, and day in the DateTime constructor.

After that, we create a DateTime struct named currentDate for January 13, 2024. In a real countdown, we would use DateTime.Today, which gives us the current date at midnight. We pin the date here, so the output stays the same whenever we run the code.

In C#, the DateTime struct is specifically designed to handle dates and times.

To learn more about DateTime, check out our other article DateTime Format In C#.

Now that we understand how the DateTime struct works, let’s continue by calculating the number of days in a static NumberOfDaysBetweenTwoDates class:

public static int CalculateDaysUntilVacation(DateTime summerVacationStart, DateTime currentDate)
{
    TimeSpan daysUntilVacation = summerVacationStart - currentDate;

    return daysUntilVacation.Days;
}

Here, we create a TimeSpan struct named daysUntilVacation. TimeSpan is designed to represent time intervals. In this case, it represents the duration between two dates.

To learn more, take a look at our other article TimeSpan in C#.

By subtracting currentDate from summerVacationStart, we calculate the time interval between these two dates. The Days property of daysUntilVacation then gives us the total number of full days until summer vacation starts.

Now, let’s put our method into action:

int daysUntilVacation = NumberOfDaysBetweenTwoDates.CalculateDaysUntilVacation(summerVacationStart, currentDate);
Console.WriteLine($"Days until summer vacation: {daysUntilVacation}");

Here, we define daysUntilVacation which utilizes the CalculateDaysUntilVacation() method that we created earlier.

With January 13, 2024 as our current date, let’s check the output:

Days until summer vacation: 140

This shows how many full days we have left until summer vacation starts.

Now we have successfully calculated the number of days between dates. But what if one of the dates was in a different time zone? 

Why Is the Day Count Sometimes One Day Short?

We’ll get to time zones shortly. Our countdown works because both dates sit at midnight, so first let’s see what happens when the current date carries a time too, say 6 p.m. on January 13:

var currentDateAndTime = new DateTime(2024, 1, 13, 18, 0, 0);
TimeSpan untilVacation = summerVacationStart - currentDateAndTime;
Console.WriteLine($"Days: {untilVacation.Days}, TotalDays: {untilVacation.TotalDays}");

Let’s check the output:

Days: 139, TotalDays: 139.25

Only 139 days and 6 hours are left until June 1. Days drops the 6 hours and returns 139, and TotalDays keeps them as a quarter of a day. Both numbers are correct for that span, but the calendar still says 140 days.

To count calendar days, we strip the time from both values with the Date property before we subtract:

Console.WriteLine($"Calendar days: {(summerVacationStart.Date - currentDateAndTime.Date).Days}");

Now we’re back to the calendar:

Calendar days: 140

That’s also why DateTime.Today suits a countdown better than DateTime.Now: Today is always midnight, so the time of day never sneaks into the result.

How Do We Count Days Between Two DateOnly Values?

DateOnly holds a date and no time, so the time-of-day problem cannot happen. It has a catch of its own, though: we can’t subtract two DateOnly values, because the type has no subtraction operator.

Instead, we use the DayNumber property. Microsoft Learn defines it as “the number of days since January 1, 0001 in the Proleptic Gregorian calendar”, so the difference between two day numbers is the number of days between the dates:

public static int CalculateDaysBetweenDates(DateOnly startDate, DateOnly endDate)
{
    return endDate.DayNumber - startDate.DayNumber;
}

Let’s count down to our vacation again, this time with DateOnly:

var vacationStart = new DateOnly(2024, 6, 1);
var today = new DateOnly(2024, 1, 13);

int daysBetween = NumberOfDaysBetweenTwoDates.CalculateDaysBetweenDates(today, vacationStart);
Console.WriteLine($"Days between {today:yyyy-MM-dd} and {vacationStart:yyyy-MM-dd}: {daysBetween}");

The result matches our DateTime version:

Days between 2024-01-13 and 2024-06-01: 140

Leap years take care of themselves. From February 28 to March 1 is two days in 2024 and one day in 2023, and the tests in our repository check both.

To learn more about the type itself, check out our article on DateOnly and TimeOnly.

How Do Time Zones Change the Day Count?

Imagine we have an international online event scheduled for September 1, 2024, at 10 a.m. in New York City, and we want to calculate how many days remain until this event from today, taking into account our local time zone.

To accurately count the days until our event we can use DateTimeOffset:

var newYork = TimeZoneInfo.FindSystemTimeZoneById("America/New_York");
var eventLocalTime = new DateTime(2024, 9, 1, 10, 0, 0);
var eventDateTime = new DateTimeOffset(eventLocalTime, newYork.GetUtcOffset(eventLocalTime));
var currentDateTime = new DateTimeOffset(2024, 1, 13, 18, 0, 0, TimeSpan.FromHours(1));

Here, we define eventDateTime, which is the event’s date and time in New York. On September 1, New York runs on daylight saving time, four hours behind UTC rather than five. So, instead of typing the offset by hand, we ask TimeZoneInfo for it, and GetUtcOffset() returns the offset that applies on that date. To do this, we use the DateTimeOffset struct which pairs a DateTime value with an offset calculating the time difference from Coordinated Universal Time (UTC). This allows us to handle dates and times in specific time zones accurately.

Then, we initialize currentDateTime, which represents the current date and time in our local time zone. Just like before, we pin it, this time to 6 p.m. on January 13, 2024, in Central Europe (UTC+1). In a real app, DateTimeOffset.Now gives us the current moment.

To learn more about DateTimeOffset, check out our great article DateTimeOffset vs DateTime in C#.

Now that currentDateTime is set, we can calculate the days remaining until the event:

public static int CalculateDaysUntilEvent(DateTimeOffset eventDateTime, DateTimeOffset currentDateTime)
{
    TimeSpan daysUntilEvent = eventDateTime - currentDateTime;

    return daysUntilEvent.Days;
}

Here, we calculate daysUntilEvent, which is the number of days between the two dates considering they are in different time zones. Then, similar to what we did before, we can access the number of whole days by using the Days property.

Now, let’s apply our new method:

Console.WriteLine($"Event offset: {eventDateTime.Offset}");

int daysUntilEvent = NumberOfDaysBetweenTwoDates.CalculateDaysUntilEvent(eventDateTime, currentDateTime);
Console.WriteLine($"Days until the event: {daysUntilEvent}");

Finally, we define daysUntilEvent, which uses the CalculateDaysUntilEvent() method we created earlier. 

After running this code, let’s check the console:

Event offset: -04:00:00
Days until the event: 231

In this scenario, 6 p.m. on January 13, 2024, in Central Europe leaves us with 231 full days until our event. On the calendar, the two dates are 232 days apart. The missing day is the time of day again: our moment is 17:00 UTC, and the event starts at 14:00 UTC, so the last day is 3 hours short of a full one.

What Happens Across a Daylight Saving Time Change?

New York moved its clocks forward on March 10, 2024. Noon on March 9 to noon on March 10 looks like one day, but only 23 hours pass. Let’s compare DateTimeOffset and DateTime across that change:

var beforeChange = new DateTimeOffset(2024, 3, 9, 12, 0, 0, TimeSpan.FromHours(-5));
var afterChange = new DateTimeOffset(2024, 3, 10, 12, 0, 0, TimeSpan.FromHours(-4));
TimeSpan offsetDifference = afterChange - beforeChange;
Console.WriteLine($"DateTimeOffset: {offsetDifference.TotalHours} hours, Days = {offsetDifference.Days}");

var localBefore = new DateTime(2024, 3, 9, 12, 0, 0);
var localAfter = new DateTime(2024, 3, 10, 12, 0, 0);
TimeSpan localDifference = localAfter - localBefore;
Console.WriteLine($"DateTime: {localDifference.TotalHours} hours, Days = {localDifference.Days}");

The two types disagree:

DateTimeOffset: 23 hours, Days = 0
DateTime: 24 hours, Days = 1

DateTimeOffset compares two moments in time, finds 23 hours between them, and returns 0 days. DateTime knows nothing about offsets. Microsoft Learn puts it this way: the subtraction “does not consider the value of the Kind property of the two DateTime values”. It subtracts the clock readings and reports a full day.

Which one is right depends on what we’re counting. For elapsed time, DateTimeOffset gives the real answer. For a countdown in days, we usually mean calendar dates, so .Date or DateOnly is the safer choice.

Conclusion

In this article, we have learned how to calculate the number of days between two dates in C#. We started with a simple yet familiar scenario: the anticipation of a summer vacation. By using the DateTime and TimeSpan structs, we were able to determine the number of days until school ends and we are free to enjoy our long break. 

We’ve also seen why the time of day and a daylight saving change can each cost us a day, and how DateOnly.DayNumber avoids both when we only care about dates.

Additionally, we talked about handling dates in different time zones with DateTimeOffset, which can be helpful when planning international events. Understanding and applying these techniques is crucial for effective date and time management in C# applications.

If weekends shouldn’t count, our article on counting the weekdays between two dates picks up where this one ends.

Tested with .NET 11.0.0 and xUnit 2.9.3.