Skip to content

Dates and a Fake Clock

The Course
•
30 min study

"Is this task overdue?" depends on today's date. A check that calls the real clock can pass today and fail tomorrow, and it can't test the boundary at all. Passing the time in, as you did with other dependencies in the last lesson, fixes that.

The date types

DateOnly is a calendar date with no time. TimeOnly is a time of day. DateTime holds both, and TimeSpan is a length of time. Choosing the most precise type avoids a whole family of bugs: a due date doesn't need midnight, or a time zone. Dates compare with < and >.

Date arithmetic C#
var due = new DateOnly(2026, 1, 31);

Console.WriteLine(due.AddDays(1).ToString("yyyy-MM-dd"));
Console.WriteLine(due.AddMonths(1).ToString("yyyy-MM-dd"));
Console.WriteLine(due.DayOfWeek);
Console.WriteLine(due < new DateOnly(2026, 2, 1));
Console.WriteLine(new DateOnly(2026, 3, 1).DayNumber - due.DayNumber);

TimeSpan length = TimeSpan.FromMinutes(90);
Console.WriteLine(length.TotalHours);
Console.WriteLine(length);
Check your prediction
Text
2026-02-01
2026-02-28
Saturday
True
29
1.5
01:30:00

Note that January 31 plus a month is February 28: AddMonths clamps to the end of the month.

Parsing dates safely

DateOnly.Parse depends on the computer's culture, so 01/02/2026 means different dates in different places. For data, fix the format with TryParseExact and use ISO yyyy-MM-dd. It's unambiguous, and sorting the text sorts the dates.

One format, no surprises C#
using System.Globalization;

foreach (string text in new[] { "2026-02-28", "2026-02-30", "02/28/2026" })
{
    bool good = DateOnly.TryParseExact(text, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateOnly date);
    Console.WriteLine(good ? date.ToString("dd MMM yyyy", CultureInfo.InvariantCulture) : $"bad: {text}");
}
Check your prediction
Text
28 Feb 2026
bad: 2026-02-30
bad: 02/28/2026

An interface for the clock

DateTime.Now is a hidden input to your program. Make it visible. In the tracker, this interface has two implementations, and the code that calculates "overdue" doesn't call the real clock at all: it takes today as a plain parameter, which is simplest of all.

Tests choose today C#
var due = new DateOnly(2026, 11, 2);
var fake = new FixedClock(new DateOnly(2026, 11, 2));

Console.WriteLine(IsOverdue(due, fake.Today));
Console.WriteLine(IsOverdue(due, fake.Today.AddDays(1)));
Console.WriteLine(IsOverdue(due, fake.Today.AddDays(-1)));

IClock real = new SystemClock();
Console.WriteLine(real.Today.Year >= 2026);

static bool IsOverdue(DateOnly due, DateOnly today) => due < today;

interface IClock
{
    DateOnly Today { get; }
}

class SystemClock : IClock
{
    public DateOnly Today => DateOnly.FromDateTime(DateTime.Now);
}

record FixedClock(DateOnly Today) : IClock;
Check your prediction
Text
False
True
False
True

The three checks use the day before, the day itself and the day after, which is impossible with the real clock unless you wait. .NET also has TimeProvider for this purpose. You'll use it in the Advanced course.

Measuring duration

For measuring how long something took, don't subtract two DateTime.Now values, since the system clock can jump. Stopwatch is built for this. The value varies between runs, so this example only checks a range.

Time a piece of work C#
using System.Diagnostics;

var watch = Stopwatch.StartNew();

long total = 0;
for (int i = 0; i < 100_000; i++)
{
    total += i;
}

watch.Stop();
Console.WriteLine(total);
Console.WriteLine(watch.Elapsed < TimeSpan.FromSeconds(30));
Check your prediction
Text
4999950000
True

Fix it: Late on the day it's due

A task is due on 2 November. This checks it at 9:30 that morning. Predict the output, then run it.

Late on the day it's due C#
DateOnly due = new DateOnly(2026, 11, 2);
DateTime now = new DateTime(2026, 11, 2, 9, 30, 0);

bool late = now > due.ToDateTime(TimeOnly.MinValue);
Console.WriteLine(late ? "late" : "on time");
Check your prediction
Text
late

ToDateTime(TimeOnly.MinValue) turns the due date into midnight at the start of that day, so any time on the due day counts as after it. The rule is about days, so compare days. Fix it.

Fix it

Turn the current time into a date, and compare two DateOnly values:

C#
DateOnly due = new DateOnly(2026, 11, 2);
DateTime now = new DateTime(2026, 11, 2, 9, 30, 0);

bool late = DateOnly.FromDateTime(now) > due;
Console.WriteLine(late ? "late" : "on time");
Text
on time

Mixing a date with a date and time is where most off-by-one-day bugs come from. Decide whether a rule is about days or moments, and convert once, at the edge, to that type.

Your turn

Exercise

Membership status

Write Status(DateOnly expires, DateOnly today), returning:

  • expired if today is after expires.
  • expires today if they're the same date.
  • renew soon if it expires within the next 30 days.
  • active otherwise.

With expiry 2026-06-30, check the boundaries by printing the result for today values of 2026-07-01, 2026-06-30, 2026-06-29, 2026-05-31 and 2026-05-30.

When it works, it prints:

Text
expired
expires today
renew soon
renew soon
active
Your workspace C#
var expires = new DateOnly(2026, 6, 30);
Console.WriteLine(expires.ToString("yyyy-MM-dd"));
Hint 1: the idea

Work out the number of days from today until expiry first. Then every case is a comparison of that one number with 0 or 30.

Hint 2: a first step

DayNumber gives each date a whole number. A switch expression with relational patterns on the difference is neat here.

Show one solution
C#
var expires = new DateOnly(2026, 6, 30);

foreach (string text in new[] { "2026-07-01", "2026-06-30", "2026-06-29", "2026-05-31", "2026-05-30" })
{
    Console.WriteLine(Status(expires, DateOnly.ParseExact(text, "yyyy-MM-dd")));
}

static string Status(DateOnly expires, DateOnly today)
{
    return (expires.DayNumber - today.DayNumber) switch
    {
        < 0 => "expired",
        0 => "expires today",
        <= 30 => "renew soon",
        _ => "active",
    };
}
Text
expired
expires today
renew soon
renew soon
active

DayNumber turns each date into a count of days, so subtracting gives a whole number of days with no time of day involved. The switch arms then read like the rules: below 0 is expired, exactly 0 is today, and up to 30 is "renew soon", which makes day 30 itself "renew soon". The test dates sit on each boundary for that reason.

Was this article helpful?

Your response is saved on this device.