Ever tried to set a delay or track time in your code and felt lost in all the numbers and calculations? I get it. Working with time such as creating countdowns, setting timers, or managing durations - can feel confusing.
The good news is that C# has a solution that makes it easy: TimeSpan
.
In this guide, I’ll show you how TimeSpan
works and why it’s a game-changer for time-based tasks. So that by the end, you’ll be able to build precise, smooth timers and schedules right in your C# projects. Ready to make timing a breeze?
Let’s dive in!
Sidenote: If you want to learn more about C#, then check out my C#/.NET Bootcamp course.
This is the only course you need to learn C# programming and master the .NET platform.
No previous coding experience required - you’ll learn C# programming from scratch, including powerful skills like data structures, object-oriented programming (OOP), and testing. All while building your own projects, so you can get hired as a C#/.NET Developer in 2025!
Check it out above, or watch the first few videos here for free.
With that out of the way, let’s get into this 5-minute tutorial…
TimeSpan
is your go-to tool in C# for handling time intervals—whether you’re working with milliseconds, hours, or days. Instead of converting hours to seconds or juggling complex calculations, TimeSpan
simplifies it all, so you can focus on what your code needs to do.
TimeSpan
brings clarity, precision, and versatility to any time-based task in your projects:
TimeSpan
makes your code easy to understand at a glance. For example, using TimeSpan.FromMinutes(30)
clearly shows a 30-minute interval, saving you from manually converting or calculating time units. This clarity becomes crucial as your project scales, making it easier to troubleshoot or adjust timingTimeSpan
, you can control timing down to the millisecond, or handle long periods like days or even weeks. This flexibility means you can use it for tasks ranging from setting a daily cache refresh in a web app to creating countdown timers in gamesTimeSpan
is an all-in-one tool for setting delays, scheduling intervals, or tracking durations—without needing extra code or libraries. Whether you’re managing quick delays, setting a high-precision timer, or scheduling recurring processes, TimeSpan
keeps your code clean, reliable, and easy to maintainCreating a TimeSpan
in C# is simple, and you’ve got several options depending on your timing needs.
Here’s a closer look at each approach, with examples of when to use them.
If you need an exact duration that combines days, hours, minutes, and seconds, you can specify each part individually. This is useful if you’re scheduling tasks with precise timing, like setting a process to run in exactly 1 day, 2 hours, 30 minutes, and 45 seconds.
For example, let’s say you’re building a backend service that processes data on a daily schedule. You could use TimeSpan
to control the exact interval between each run:
TimeSpan interval = new TimeSpan(1, 2, 30, 45); // 1 day, 2 hours, 30 minutes, 45 seconds
Here, TimeSpan
knows the order: days, hours, minutes, seconds, and milliseconds (if you add a fifth value). This method is perfect for projects needing precision across longer durations.
For many tasks, you only need a single unit like minutes or hours. .NET provides built-in methods that make it easy to set these intervals without conversions. Here’s how these methods fit common use cases:
TimeSpan sessionTimeout = TimeSpan.FromMinutes(30); // 30-minute session timeout
TimeSpan retryDelay = TimeSpan.FromSeconds(5); // 5-second delay before retrying a task
Using these methods makes your code readable and keeps your intent clear. When you write TimeSpan.FromMinutes(30)
, anyone reading your code immediately understands it’s a 30-minute interval.
Negative values are helpful if you track time that has passed since an event, like overdue tasks or countdowns. This is especially useful in situations where you need to display the elapsed time since a deadline or to track tasks that are past due.
For example
In project management software, you might show how late a task is. TimeSpan
makes this easy with negative intervals:
TimeSpan overdueTime = TimeSpan.FromMinutes(-10); // 10 minutes past due
Console.WriteLine(overdueTime); // Output: "-00:10:00"
This negative value represents the “backwards” interval, making it clear how far a task is overdue. Negative TimeSpan
values allow you to display these “past-due” states, which can be invaluable for reminders or alerts in applications that depend on timing accuracy.
Each TimeSpan
method offers specific advantages based on your timing needs.
TimeSpan.FromMinutes()
for a 30-minute timeoutFromDays()
or the fully specified constructor (with days, hours, minutes, etc.) helpfulOnce you’ve created a TimeSpan
, you’ll often want to display it in a user-friendly way, so let's look at a few options:
ToString()
One of the simplest ways to format a TimeSpan
is by using .ToString()
. This method automatically organizes days, hours, minutes, and seconds into a standard format:
TimeSpan processDuration = new TimeSpan(1, 2, 30, 45);
Console.WriteLine(processDuration.ToString()); // Output: "1.02:30:45"
This output, “1.02:30:45,” represents 1 day, 2 hours, 30 minutes, and 45 seconds. It’s ideal for logs, dashboards, or anywhere clarity is key.
.ToString("c")
If you only need specific parts of the TimeSpan
, custom formatting can help. The "c"
format, for example, gives a compact, clean display—perfect for showing hours and minutes only:
TimeSpan taskDuration = TimeSpan.FromMinutes(90);
Console.WriteLine(taskDuration.ToString("c")); // Output: "01:30:00"
With ToString("c")
, you get a simple, readable format (1 hour and 30 minutes) that works great in timers or logs.
For added control, you can use other custom format specifiers to tailor the display. These make it easy to adapt TimeSpan
for your exact needs, whether it’s a countdown timer, high-precision display, or any other timing feature.
Here are a few handy ones:
"hh\\:mm\\:ss"
– Shows hours, minutes, and seconds"dd\\:hh\\:mm"
– Displays days, hours, and minutes, helpful for long intervals"mm\\:ss\\.fff"
– Shows minutes, seconds, and milliseconds for precise timingSay you’re timing an event and need hours, minutes, and seconds. You’d format it like this:
TimeSpan preciseDuration = TimeSpan.FromSeconds(3675); // 1 hour, 1 minute, and 15 seconds
Console.WriteLine(preciseDuration.ToString("hh\\:mm\\:ss")); // Output: "01:01:15"
Let’s say you’re creating a 5-minute countdown timer for a game, and you want it to show the remaining time in minutes and seconds, updating every second as it ticks down.
With TimeSpan
, you can define this time interval, and then use a loop to display it dynamically, simulating an active countdown, like so:
TimeSpan countdown = TimeSpan.FromMinutes(5);
while (countdown > TimeSpan.Zero)
{
Console.Clear();
Console.WriteLine($"Countdown: {countdown.ToString("mm\\:ss")}");
await Task.Delay(TimeSpan.FromSeconds(1));
countdown = countdown.Add(TimeSpan.FromSeconds(-1));
}
In this example, we start by defining a 5-minute TimeSpan
. The while
loop runs as long as countdown
is greater than zero, updating the display with each second.
Here’s a breakdown of the key parts:
Console.Clear();
clears the console at the start of each loop iteration, so only the current time appears on the screenConsole.WriteLine(...)
displays the remaining time in a "mm" formatawait Task.Delay(TimeSpan.FromSeconds(1));
pauses for one second without blocking, creating the countdown effectcountdown = countdown.Add(TimeSpan.FromSeconds(-1));
subtracts one second from the countdown on each loop iterationThis approach lets your countdown update smoothly, ticking down in real-time from "04:59," "04:58," and so on, until it reaches "00:00." This setup is ideal for games or applications where users need to see a visible, real-time countdown.
Sidenote: Learn more about await and async here. Also, learn more about string interpolation here.
Using TimeSpan
is generally straightforward, but there are a few common pitfalls to avoid:
TimeSpan.FromMinutes(30)
and new TimeSpan(0, 30, 0)
to avoid inaccurate timingTimeSpan
Issues: Negative TimeSpan
values are helpful, but remember to use them correctly in conditional checks or displays, as they may appear differently based on your formatTimeSpan.Zero
: Here's the thing - TimeSpan.Zero
represents an interval of zero. Use it in comparisons or as a default, but avoid unintended behavior by checking it carefully in your conditionsNow it’s your turn to put TimeSpan
to work. TimeSpan
is truly a game-changer for handling time in C#. From setting session timeouts to creating countdowns and scheduling tasks, TimeSpan
manages the heavy lifting, letting you focus on your project’s core functionality while keeping your code clean, readable, and precise.
Incorporating TimeSpan
brings a level of polish to time-dependent features—whether it’s logging durations, displaying countdowns, or managing recurring events. Its intuitive format options make timing easy to work with, clear to understand, and simple to maintain, giving your users dependable, accurate displays.
Ready to level up your C# skills? Start experimenting with TimeSpan
in your projects and explore its flexible options. You’ll quickly see how it transforms time management, bringing both efficiency and professionalism to your code.
Don’t forget - if you want to learn more about C# as well as the .NET platform, check out my complete course:
No previous coding experience required - you’ll learn C# programming from scratch, including powerful skills like data structures, object-oriented programming (OOP), and testing. All while building your own projects, so you can get hired as a C#/.NET Developer in 2025!
It’s the only course you need to learn C# programming and master the .NET platform. You’ll learn everything from scratch and put your skills to the test with exercises, quizzes, and projects!
Plus, once you join, you'll have the opportunity to ask questions in our private Discord community from me, other students, and working developers.
There's always someone online 24/7 happy to help. It's by far the thing that my students always tell me is the best part of their experience. Hope you decide to take my course and if you do, make sure to come say hi on Discord!
Check it out above, or watch the first few videos here for free.