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 durationTotalDays- the full duration expressed in days, including fractionsHours,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
DateTimeis the pin's position. - Subtracting two
DateTimevalues 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 timeTimeSpan= the duration between two moments.Date= remove the time and keep only the calendar date
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.
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:
startis2024-06-01 14:00:00.endis2024-06-04 09:00:00.start.Datebecomes2024-06-01 00:00:00.end.Datebecomes2024-06-04 00:00:00.- C# subtracts the two
DateTimevalues. - The result is a
TimeSpanrepresenting 3 days. diff.Daysreturns3.- The program prints .
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
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
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 = DateTime(, , , , , );
Console.WriteLine((end - start).Days);
Comparisons
| Approach | What it returns | Best when | Example |
|---|---|---|---|
(end - start).Days | Whole-day component of the duration | You want whole days from a TimeSpan | 2 |
(end - start).TotalDays | Exact duration in days, including fractions | Partial days matter | 2.25 |
(end.Date - start.Date).Days | Calendar day difference | You want to ignore time | 7 |
Math.Abs((end.Date - start.Date).Days) | Positive calendar day difference | Date order does not matter |
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
DateTimevalues gives aTimeSpan - Use
.Daysfor whole days - Use
.TotalDaysfor fractional days - Use
.Dateif you want to ignore time - Watch for negative results if dates are reversed
- Add
1only 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
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:
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
- Read two dates from the user.
- Parse the input into valid
DateTimevalues. - Ignore the time portion when calculating the difference.
- Show the number of days between the dates.
- Prevent invalid input or clearly report parsing errors.
Keep learning
Related questions
AddTransient vs AddScoped vs AddSingleton in ASP.NET Core Dependency Injection
Learn the differences between AddTransient, AddScoped, and AddSingleton in ASP.NET Core DI with examples and practical usage.
C# Type Checking Explained: typeof vs GetType() vs is
Learn when to use typeof, GetType(), and is in C#. Understand exact type checks, inheritance, and safe type testing clearly.
C# Version Numbers Explained: C# vs .NET Framework and Why “C# 3.5” Is Incorrect
Learn the correct C# version numbers, how they map to .NET releases, and why terms like C# 3.5 are inaccurate and confusing.