Question

How to Calculate the Difference Between Two Dates in C#

csharpdate

Question

How can I calculate the number of days between two dates in C#?

Short Answer

By the end of this page, you will understand how C# calculates the difference between two dates using DateTime and TimeSpan, how to get the number of days correctly, and how to avoid common mistakes involving time portions, negative results, and date-only comparisons.

Concept

In C#, the usual way to find the difference between two dates is to subtract one DateTime from another. That subtraction returns a TimeSpan, which represents a duration.

For example:

DateTime start = new DateTime(2024, 1, 1);
DateTime end = new DateTime(2024, 1, 10);
TimeSpan difference = end - start;

Here, difference stores the amount of time between the two dates.

The TimeSpan type gives you several useful properties:

  • Days - the whole-day part of the duration
  • TotalDays - the full duration expressed in days, including fractions
  • Hours, Minutes, Seconds - individual parts of the duration

This matters because dates in real programs are often used for:

  • booking systems
  • deadlines
  • age or membership calculations
  • reports and analytics
  • scheduling tasks

A very important detail is that DateTime usually contains both a date and a time. If the two values have different times, the result may not be a whole number of days.

For example, these two values are less than 1 day apart:

DateTime a = new DateTime(2024, 1, 1, 12, 0, 0);
DateTime b = new DateTime(2024, 1, 2, 6, 0, 0);

TimeSpan diff = b - a;
Console.WriteLine(diff.TotalDays); // 0.75
Console.WriteLine(diff.Days);      // 0

If you want to compare only calendar dates, ignore the time portion by using .Date:

int days = (end.Date - start.Date).Days;

That is often the simplest and safest answer when the goal is the number of calendar days between two dates.

Mental Model

Think of a DateTime as a point on a timeline, like a pin placed on a long measuring tape.

  • A DateTime is the pin's position.
  • Subtracting two DateTime values measures the distance between the pins.
  • That measured distance is a TimeSpan.

If the pins are placed exactly at midnight on different dates, the distance is easy to read as whole days.

If one pin is placed at 3 PM and another at 9 AM, the distance includes partial days too. That is why time values can affect the result.

So the main idea is:

  • DateTime = a moment in time
  • TimeSpan = the duration between two moments
  • .Date = remove the time and keep only the calendar date
Take Quiz

Syntax and Examples

The basic syntax is:

TimeSpan difference = endDate - startDate;
int wholeDays = difference.Days;
double exactDays = difference.TotalDays;

Example 1: Whole number of days between two dates

DateTime startDate = new DateTime(2024, 5, 1);
DateTime endDate = new DateTime(2024, 5, 8);

int days = (endDate - startDate).Days;
Console.WriteLine(days); // 7

This works because both dates are created without a time, so they default to midnight.

Example 2: Ignore the time portion

DateTime startDate = new DateTime(2024, 5, 1, 15, 30, 0);
DateTime endDate = new DateTime(2024, 5, 8, 9, 0, 0);

int days = (endDate.Date - startDate.Date).Days;
Console.WriteLine(days); // 7

Even though the times are different, .Date removes them before subtraction.

Example 3: Get fractional days

DateTime startDate = new DateTime(2024, 5, 1, 12, 0, 0);
DateTime endDate = new DateTime(2024, 5, 3, 18, 0, 0);

double totalDays = (endDate - startDate).TotalDays;
Console.WriteLine(totalDays); // 2.25

Use TotalDays when partial days matter.

Example 4: Make the result always positive

DateTime first = new DateTime(2024, 5, 10);
DateTime second = new DateTime(2024, 5, 3);

int days = Math.Abs((second.Date - first.Date).Days);
Console.WriteLine(days); // 7

This is useful when you only care about the distance between two dates, not their order.

Step by Step Execution

Consider this example:

DateTime start = new DateTime(2024, 6, 1, 14, 0, 0);
DateTime end = new DateTime(2024, 6, 4, 9, 0, 0);

TimeSpan diff = end.Date - start.Date;
Console.WriteLine(diff.Days);

Step by step:

  1. start is 2024-06-01 14:00:00.
  2. end is 2024-06-04 09:00:00.
  3. start.Date becomes 2024-06-01 00:00:00.
  4. end.Date becomes 2024-06-04 00:00:00.
  5. C# subtracts the two DateTime values.
  6. The result is a TimeSpan representing 3 days.
  7. diff.Days returns 3.
  8. The program prints 3.

Now compare it with this version:

DateTime start = new DateTime(2024, 6, 1, 14, 0, 0);
DateTime end = new DateTime(2024, 6, 4, 9, 0, 0);

TimeSpan diff = end - start;
Console.WriteLine(diff.TotalDays);
Console.WriteLine(diff.Days);

What happens here:

  1. The time values are not removed.
  2. The actual difference is 2 days and 19 hours.
  3. diff.TotalDays returns about 2.791666....
  4. diff.Days returns 2 because it gives the whole-day component.

This shows why you should decide first whether you want:

  • calendar day difference, or
  • exact time-based difference

Real World Use Cases

Calculating days between dates appears in many real applications.

Common use cases

  • Booking systems: count the number of nights between check-in and check-out dates
  • Task tracking: find how many days remain until a deadline
  • Reporting: measure how many days an order took to complete
  • Subscriptions: calculate trial period length
  • HR systems: count vacation days between two dates
  • Data processing: group or filter records by age in days

Example: Days until a deadline

DateTime today = DateTime.Today;
DateTime deadline = new DateTime(2024, 12, 31);

int daysLeft = (deadline - today).Days;
Console.WriteLine($"Days left: {daysLeft}");

Example: Hotel stay length

DateTime checkIn = new DateTime(2024, 7, 10);
DateTime checkOut = new DateTime(2024, 7, 15);

int nights = (checkOut.Date - checkIn.Date).Days;
Console.WriteLine($"Stay length: {nights} nights");

Example: Record age in days

DateTime createdAt = new DateTime(2024, 4, 1);
int ageInDays = (DateTime.Today - createdAt.Date).Days;
Console.WriteLine(ageInDays);
Take Quiz

Real Codebase Usage

In real codebases, developers usually do more than just subtract two dates. They also validate inputs and choose whether the time portion matters.

Common patterns

Guard clauses

Check for invalid input early:

int GetDaysBetween(DateTime start, DateTime end)
{
    if (end < start)
        throw new ArgumentException("End date cannot be earlier than start date.");

    return (end.Date - start.Date).Days;
}

Early return for optional values

int? GetDaysBetween(DateTime? start, DateTime? end)
{
    if (start == null || end == null)
        return null;

    return (end.Value.Date - start.Value.Date).Days;
}

Validation in APIs or forms

Developers often validate date ranges before saving data:

if (booking.EndDate.Date <= booking.StartDate.Date)
{
    return BadRequest("End date must be after start date.");
}

Encapsulating logic in a helper method

public static class DateUtils
{
    public static int DaysBetween(DateTime start, DateTime end)
    {
        return (end.Date - start.Date).Days;
    }
}

This makes the intent clearer and avoids repeating logic everywhere.

Choosing the right type

If you only need calendar dates, modern C# projects may use DateOnly instead of DateTime.

DateOnly start = new DateOnly(2024, 5, 1);
DateOnly end = new DateOnly(2024, 5, 10);
int days = end.DayNumber - start.DayNumber;

This avoids time-of-day problems entirely.

Common Mistakes

1. Forgetting that DateTime includes time

Broken example:

DateTime start = new DateTime(2024, 5, 1, 23, 0, 0);
DateTime end = new DateTime(2024, 5, 2, 1, 0, 0);

int days = (end - start).Days;
Console.WriteLine(days); // 0

A beginner might expect 1, but the actual difference is only 2 hours.

Fix:

int days = (end.Date - start.Date).Days;

2. Using Days when TotalDays is needed

Broken example:

DateTime start = new DateTime(2024, 5, 1, 12, 0, 0);
DateTime end = new DateTime(2024, 5, 3, 18, 0, 0);

Console.WriteLine((end - start).Days); // 2

This drops the extra 6 hours.

Fix:

Console.WriteLine((end - start).TotalDays); // 2.25

3. Ignoring negative results

Broken example:

DateTime start = new DateTime(2024, 5, 10);
DateTime end = new DateTime(2024, 5, 1);

Console.WriteLine((end - start).Days); // -9

Fix options:

  • validate the order of dates
  • or use Math.Abs(...) if order does not matter
int days = Math.Abs((end.Date - start.Date).Days);

4. Confusing inclusive and exclusive counting

If something starts on June 1 and ends on June 3:

int days = (new DateTime(2024, 6, 3) - new DateTime(2024, 6, 1)).Days;
Console.WriteLine(days); // 2

That means there are 2 days between the dates.

If you want to count both dates inclusively, add 1:

int inclusiveDays = (end.Date - start.Date).Days + 1;

5. Mixing local time and UTC incorrectly

If one value is local time and another is UTC, the result can be confusing.

Prefer to keep both values in the same time standard before subtracting them.

Comparisons

ApproachWhat it returnsBest whenExample
(end - start).DaysWhole-day component of the durationYou want whole days from a TimeSpan2
(end - start).TotalDaysExact duration in days, including fractionsPartial days matter2.25
(end.Date - start.Date).DaysCalendar day differenceYou want to ignore time7
Math.Abs((end.Date - start.Date).Days)Positive calendar day differenceDate order does not matter7
DateOnly subtraction via DayNumberDate-only day differenceYou do not want time-of-day issuesend.DayNumber - start.DayNumber

Days vs TotalDays

PropertyTypeIncludes fractions?Example result
DaysintNo2
TotalDaysdoubleYes2.25

DateTime vs DateOnly

TypeIncludes time?Good for
DateTimeYesTimestamps, events, logs
DateOnlyNoBirth dates, bookings, deadlines by date
Take Quiz

Cheat Sheet

// Exact duration
TimeSpan diff = endDate - startDate;

// Whole days only
int days = diff.Days;

// Exact days including fractions
double totalDays = diff.TotalDays;

// Ignore time portion
int calendarDays = (endDate.Date - startDate.Date).Days;

// Always positive
int positiveDays = Math.Abs((endDate.Date - startDate.Date).Days);

Quick rules

  • Subtracting two DateTime values gives a TimeSpan
  • Use .Days for whole days
  • Use .TotalDays for fractional days
  • Use .Date if you want to ignore time
  • Watch for negative results if dates are reversed
  • Add 1 only if you need inclusive counting
  • Keep both dates in the same time standard when working with UTC/local time

Common patterns

int daysBetween = (end.Date - start.Date).Days;
double exactDaysBetween = (end - start).TotalDays;
int safePositiveDays = Math.Abs((end.Date - start.Date).Days);

Edge cases

  • Different time values can change the result
  • Reversed dates produce negative durations
  • Days does not mean rounded total days; it means the whole-day part
  • Date-only business logic is often clearer with DateOnly

FAQ

How do I calculate days between two dates in C#?

Subtract one DateTime from another and read the result from the TimeSpan, usually with .Days or .TotalDays.

What is the difference between Days and TotalDays in C#?

Days returns only the whole-day part as an integer. TotalDays returns the full duration as a double, including fractions.

How do I ignore the time when comparing dates in C#?

Use the .Date property before subtracting:

int days = (end.Date - start.Date).Days;

Why does my date difference return 0 days?

Because the difference may be less than 24 hours. In that case, .Days returns 0 even if the dates are on different calendar days.

How do I get a positive number of days between two dates?

Use Math.Abs:

int days = Math.Abs((end.Date - start.Date).Days);

Should I use DateTime or DateOnly?

Use DateTime when time matters. Use DateOnly when you only care about calendar dates.

How do I count both the start and end dates?

Use inclusive counting by adding 1:

int inclusiveDays = (end.Date - start.Date).Days + 1;
Take Quiz

Mini Project

Description

Build a small C# console program that asks for two dates and prints the number of days between them. This project demonstrates how to parse user input, work with DateTime, ignore time when needed, and handle invalid date order safely.

Goal

Create a console app that reads two dates and displays the calendar day difference between them.

Requirements

  1. Read two dates from the user.
  2. Parse the input into valid DateTime values.
  3. Ignore the time portion when calculating the difference.
  4. Show the number of days between the dates.
  5. Prevent invalid input or clearly report parsing errors.
Take Quiz

Keep learning

Related questions

View more