CodeGym /Courses /C# SELF /Calculations and Helper Classes for Dates and Time

Calculations and Helper Classes for Dates and Time

C# SELF
Level 15 , Lesson 4
Available

1. Main Tasks When Working with Date and Time

Working with dates and time often causes a slight (and sometimes not so slight) sense of panic even for experienced devs. You'll have to compare dates, calculate intervals, add or subtract days/months/years, calculate age, figure out the day of the week, and a bunch of other stuff.

All of this is typical for task trackers and calendars, subscription or membership accounting, financial calculations, statistical reports, and of course, for interview questions (like "calculate the number of working days between two dates").

In C# and .NET there are built-in classes and methods for all this. And the best part — most calculations are done through an object-oriented, super safe and clear API.

2. The TimeSpan Struct — Measuring Time Intervals

It all starts with the TimeSpan struct. It's a "chunk" of time: like, 5 days, 3 hours, 7 minutes, and 21 seconds.

How to Create a TimeSpan?

You can "subtract" two dates, or create it directly:

// The difference between two dates is always TimeSpan!
DateTime start = new DateTime(2025, 5, 1, 7, 0, 0);
DateTime end = new DateTime(2025, 5, 2, 11, 30, 0);

TimeSpan duration = end - start; // Pure magic!
Console.WriteLine(duration); // 1.04:30:00 (1 day, 4 hours, 30 minutes)

You can also create a TimeSpan directly using the constructor params:

TimeSpan span = new TimeSpan(2, 14, 18, 0); // 2 days, 14 hours, 18 minutes, 0 seconds
Console.WriteLine(span); // 2.14:18:00

Another way — use static methods, which are often more readable:

TimeSpan fiveMinutes = TimeSpan.FromMinutes(5);
TimeSpan twoHours = TimeSpan.FromHours(2);
TimeSpan oneWeek = TimeSpan.FromDays(7);

What Properties Does TimeSpan Have?

Property Description
Days
Whole number of days
Hours
Hour part
Minutes
Minute part
Seconds
Second part
TotalDays
Time in days (fractional)
TotalHours
Time in hours (fractional)
TotalMinutes
Time in minutes (fractional)
TotalSeconds
Time in seconds (fractional)
Console.WriteLine($"Days: {duration.Days}, Total hours: {duration.TotalHours}");

How to Add/Subtract TimeSpan to a Date?

DateTime now = DateTime.Now;
DateTime future = now.Add(duration); // Added duration to now
DateTime past = now.Subtract(TimeSpan.FromDays(10)); // Minus 10 days

Console.WriteLine(future);
Console.WriteLine(past);

3. Date Calculator: Calculating the Difference Between Dates

A skill you'll need basically always. For example, someone wants to know how long until vacation, or when the free trial ends.

DateTime today = DateTime.Today;
DateTime vacation = new DateTime(2025, 8, 1);
TimeSpan untilVacation = vacation - today;

Console.WriteLine($"Until vacation: {untilVacation.Days} days left!");

Heads up: if you're subtracting just "dates" without time (using DateTime.Date or DateTime.Today), the result is always a whole number of days. But if even one date has a time, the difference is fractional.


int days = (vacation - today).TotalDays; // Compile error! TotalDays is double

If you need a whole number — use .Days or cast to int with (int)TotalDays.

4. Adding and Subtracting Time: AddDays, AddMonths, AddHours, ...

C# doesn't make you count days in each month, leap years, or any of that pain. Just use:

DateTime orderDate = new DateTime(2024, 4, 20);
DateTime deliveryDate = orderDate.AddDays(14); // In 2 weeks

Console.WriteLine($"The item will be delivered on {deliveryDate.ToShortDateString()}");
Method What it adds (or subtracts if negative)
AddDays(double)
Days (supports fractions, like 1.5 days)
AddMonths(int)
Months (automatically handles month length)
AddYears(int)
Years (even leap years)
AddHours(double)
Hours
AddMinutes(double)
Minutes
AddSeconds(double)
Seconds
DateTime birthday = new DateTime(2000, 2, 29);
DateTime nextYear = birthday.AddYears(1); // 2001-02-28 (not the 29th, since 2001 isn't leap)
Console.WriteLine(nextYear.ToShortDateString()); // 02/28/2001

Don't forget: all these methods return a new date instance, the original date doesn't change!

var dt = DateTime.Now;
dt.AddDays(5); // This does NOT change dt!
dt = dt.AddDays(5); // Now it changes

5. Helper Methods for Calculations

Calculating the Day of the Week

Most of the time you can use the .DayOfWeek property:

DateTime examDate = new DateTime(2025, 6, 19);
DayOfWeek day = examDate.DayOfWeek;
Console.WriteLine(day); // Wednesday

You can cast it to an int:

int number = (int)day; // Sunday == 0, Monday == 1, and so on

Checking "Today", "Yesterday", "Tomorrow"

Simple comparisons:

DateTime date = new DateTime(2025, 6, 18);

if (date.Date == DateTime.Today)
    Console.WriteLine("Today!");
else if (date.Date == DateTime.Today.AddDays(-1))
    Console.WriteLine("Yesterday!");
else if (date.Date == DateTime.Today.AddDays(1))
    Console.WriteLine("Tomorrow!");

Calculating Age

One of the most common tasks — correctly calculating a person's age. Just subtracting years doesn't always work right:

public static int CalculateAge(DateTime birthDate, DateTime currentDate)
{
    int age = currentDate.Year - birthDate.Year;
    
    // If the birthday hasn't happened yet this year
    if (currentDate.Month < birthDate.Month || 
        (currentDate.Month == birthDate.Month && currentDate.Day < birthDate.Day))
    {
        age--;
    }
    
    return age;
}

// Usage
DateTime birth = new DateTime(1990, 8, 15);
DateTime today = DateTime.Today;
int age = CalculateAge(birth, today);
Console.WriteLine($"Age: {age} years");

Working with Working Days

You often need to count the number of working days between dates, skipping weekends:

public static int CountWorkingDays(DateTime startDate, DateTime endDate)
{
    int workingDays = 0;
    DateTime current = startDate;
    
    while (current <= endDate)
    {
        if (current.DayOfWeek != DayOfWeek.Saturday && 
            current.DayOfWeek != DayOfWeek.Sunday)
        {
            workingDays++;
        }
        current = current.AddDays(1);
    }
    
    return workingDays;
}

6. How the Main Classes Are Connected

graph TD
    A(DateTime) --subtraction--> B(TimeSpan)
    A2(DateTime) --AddDays, AddMonths--> A
    A --ToLocalTime/ToUniversalTime--> C(DateTimeOffset)
    D(DateOnly) --ToDateTime--> A
    E(TimeOnly) --ToTimeSpan--> B
    A --DayOfWeek, Day, Month, Year--> F(Numeric properties)
    B(TimeSpan) --TotalDays, TotalHours, ...--> G(Duration properties)

7. Quick "Cheat Sheet": What to Do If...

Task What to use Example
Find the difference between dates
TimeSpan duration = d2 - d1
(d2 - d1).Days
Add 2 weeks to a date
date.AddDays(14)
date.AddDays(14)
Calculate age Formula with
.Year
and checking month/day
See section above
Get/set only the date
DateOnly
DateOnly.FromDateTime(DateTime.Now)
Get/set only the time
TimeOnly
TimeOnly.FromDateTime(DateTime.Now)
Compare dates Operators
<
,
>
,
==
,
.CompareTo()
if (d1 < d2) ...
Convert to another time zone
DateTimeOffset + ToOffset
dto.ToOffset(TimeSpan.FromHours(3))
Find the week number in the year
Calendar.GetWeekOfYear()
see docs
Find the day of the week
date.DayOfWeek
Count working days Loop with
DayOfWeek
check
See section above
2
Task
C# SELF, level 15, lesson 4
Locked
Difference Between Dates
Difference Between Dates
2
Task
C# SELF, level 15, lesson 4
Locked
Day of the Week
Day of the Week
1
Survey/quiz
Working with Dates, level 15, lesson 4
Unavailable
Working with Dates
Working with dates, time, and time zones
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION