🎁 Give the #1 gift request of 2024... a ZTM membership gift card! 🎁

Beginner's Guide to TimeSpan in C# (With Code Examples)

Claudio Bernasconi
Claudio Bernasconi
hero image

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.

learn c sharp

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…

What is TimeSpan in C#?

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.

Why use TimeSpan?

TimeSpan brings clarity, precision, and versatility to any time-based task in your projects:

  • Readability: 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 timing
  • Precision: With TimeSpan, 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 games
  • Versatility: TimeSpan 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 maintain

How to create a TimeSpan

Creating 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.

Specifying days, hours, minutes, and seconds

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.

Using static methods for common intervals

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.FromDays() – Perfect for daily tasks, like refreshing a report every day
  • TimeSpan.FromHours() – Useful for hourly schedules, like sending an automated email or syncing data every hour
  • TimeSpan.FromMinutes() – Ideal for session timeouts or shorter intervals, like a quick timeout feature
  • TimeSpan.FromSeconds() – Handy for quick delays or countdowns, such as retrying a task after a short delay
  • TimeSpan.FromMilliseconds() – Ideal for high-precision timing, like animations or micro-delays.
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.

Handling negative TimeSpans

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.

Which TimeSpan methods are best for different tasks?

Each TimeSpan method offers specific advantages based on your timing needs.

  • If you’re managing session timeouts, you might want a method that’s readable and precise, like TimeSpan.FromMinutes() for a 30-minute timeout
  • But when working with recurring events or complex schedules, you’ll find methods like FromDays() or the fully specified constructor (with days, hours, minutes, etc.) helpful

How to display TimeSpan values

Once 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:

Option #1). Formatting TimeSpan output with 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.

Option #2). Customizing the format with .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.

Some more options for more specific needs

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 timing

Say 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"

Practical Scenario: Building a countdown timer for a game or app

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 screen
  • Console.WriteLine(...) displays the remaining time in a "mm" format
  • await Task.Delay(TimeSpan.FromSeconds(1)); pauses for one second without blocking, creating the countdown effect
  • countdown = countdown.Add(TimeSpan.FromSeconds(-1)); subtracts one second from the countdown on each loop iteration

This 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.

Common errors when using TimeSpan

Using TimeSpan is generally straightforward, but there are a few common pitfalls to avoid:

  1. Misunderstanding Constructor Order: Remember, the constructor expects days, hours, minutes, seconds, and milliseconds (in that order). Mixing these up can lead to unintended intervals
  2. Forgetting Time Units: Be careful with the differences between methods like TimeSpan.FromMinutes(30) and new TimeSpan(0, 30, 0) to avoid inaccurate timing
  3. Negative TimeSpan 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 format
  4. Ignoring TimeSpan.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 conditions

Now it's your turn to try this out

Now 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.

P.S.

Don’t forget - if you want to learn more about C# as well as the .NET platform, check out my complete course:

learn c sharp

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.

More from Zero To Mastery

5 Reasons Why You Should Learn C# preview
5 Reasons Why You Should Learn C#

It's been 23 years since C# went live, but it's still growing in popularity. Find out why (+ why you should learn this language ASAP to advance your career).

Best Programming Languages To Learn In 2025 preview
Best Programming Languages To Learn In 2025

Want to know the best programming languages to learn in 2025? See the top 10 picks for high-paying jobs, future-proof skills, and unstoppable growth.

What Is C# Used For? Pretty Much Everything! preview
What Is C# Used For? Pretty Much Everything!

C# can build anything from Desktop + Web Apps to Cloud Integrations, Games, Automations + more. In this guide, I walk through why it works so well in each area.