DateTime Conversion
TimeSpan
C# Programming
Date Manipulation
Coding Techniques

Convert DateTime to TimeSpan

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In C#, DateTime represents a specific point in time (e.g., "March 1, 2026 at 3:45 PM") while TimeSpan represents a duration or interval (e.g., "3 hours and 45 minutes"). Converting between them is a common operation for calculating elapsed time, extracting the time-of-day component, or measuring durations between events.

Extracting Time-of-Day as TimeSpan

The most common "conversion" is getting the time-of-day portion of a DateTime as a TimeSpan:

csharp
1DateTime now = DateTime.Now; // e.g., 2026-03-01 15:45:30
2TimeSpan timeOfDay = now.TimeOfDay;
3// Result: 15:45:30 (hours since midnight)
4
5Console.WriteLine(timeOfDay.Hours);     // 15
6Console.WriteLine(timeOfDay.Minutes);   // 45
7Console.WriteLine(timeOfDay.Seconds);   // 30
8Console.WriteLine(timeOfDay.TotalHours); // 15.7583...

Calculating Duration Between Two DateTimes

Subtracting two DateTime values produces a TimeSpan:

csharp
1DateTime start = new DateTime(2026, 3, 1, 9, 0, 0);
2DateTime end = new DateTime(2026, 3, 1, 17, 30, 0);
3
4TimeSpan duration = end - start;
5// Result: 08:30:00
6
7Console.WriteLine(duration.TotalHours);   // 8.5
8Console.WriteLine(duration.TotalMinutes); // 510
9Console.WriteLine(duration.TotalSeconds); // 30600

Multi-Day Durations

csharp
1DateTime projectStart = new DateTime(2026, 1, 15);
2DateTime projectEnd = new DateTime(2026, 3, 1);
3
4TimeSpan projectDuration = projectEnd - projectStart;
5
6Console.WriteLine(projectDuration.Days);       // 45
7Console.WriteLine(projectDuration.TotalDays);  // 45.0
8Console.WriteLine(projectDuration.TotalHours); // 1080.0

TimeSpan from DateTime Components

Create a TimeSpan manually from a DateTime's components:

csharp
1DateTime dt = new DateTime(2026, 3, 1, 14, 30, 45);
2
3// Extract time components into a TimeSpan
4TimeSpan ts = new TimeSpan(dt.Hour, dt.Minute, dt.Second);
5// Result: 14:30:45
6
7// With days
8TimeSpan tsWithDays = new TimeSpan(dt.Day, dt.Hour, dt.Minute, dt.Second);

Elapsed Time Since a Reference Point

Calculate time elapsed since midnight, epoch, or any reference:

csharp
1// Time since midnight (same as TimeOfDay)
2TimeSpan sinceMidnight = DateTime.Now - DateTime.Today;
3
4// Time since Unix epoch
5TimeSpan sinceEpoch = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
6Console.WriteLine($"Unix timestamp: {sinceEpoch.TotalSeconds:F0}");
7
8// Time since app started
9DateTime appStart = DateTime.UtcNow;
10// ... later ...
11TimeSpan uptime = DateTime.UtcNow - appStart;
12Console.WriteLine($"Uptime: {uptime.TotalMinutes:F1} minutes");

Adding TimeSpan to DateTime

The reverse operation — adding a duration to a point in time:

csharp
1DateTime now = DateTime.Now;
2
3// Add 2 hours and 30 minutes
4TimeSpan duration = new TimeSpan(2, 30, 0);
5DateTime later = now.Add(duration);
6
7// Or use convenience methods
8DateTime tomorrow = now.AddDays(1);
9DateTime nextHour = now.AddHours(1);
10DateTime fiveMinutesAgo = now.AddMinutes(-5);

Formatting TimeSpan

csharp
1TimeSpan ts = new TimeSpan(1, 14, 30, 45); // 1 day, 14h, 30m, 45s
2
3// Standard formatting
4Console.WriteLine(ts.ToString());              // 1.14:30:45
5Console.WriteLine(ts.ToString(@"hh\:mm\:ss")); // 14:30:45
6Console.WriteLine(ts.ToString(@"d\.hh\:mm"));  // 1.14:30
7
8// Custom human-readable
9string FormatDuration(TimeSpan span)
10{
11    if (span.TotalDays >= 1)
12        return $"{span.Days}d {span.Hours}h {span.Minutes}m";
13    if (span.TotalHours >= 1)
14        return $"{span.Hours}h {span.Minutes}m";
15    return $"{span.Minutes}m {span.Seconds}s";
16}
17
18Console.WriteLine(FormatDuration(ts)); // "1d 14h 30m"

Using Stopwatch for Precise Timing

For measuring code execution time, prefer Stopwatch over DateTime subtraction:

csharp
1using System.Diagnostics;
2
3var stopwatch = Stopwatch.StartNew();
4
5// Code to measure
6Thread.Sleep(1500);
7
8stopwatch.Stop();
9TimeSpan elapsed = stopwatch.Elapsed;
10
11Console.WriteLine($"Elapsed: {elapsed.TotalMilliseconds:F2} ms");
12Console.WriteLine($"Elapsed: {elapsed.TotalSeconds:F3} s");

Stopwatch uses high-resolution timers and is not affected by system clock changes.

DateTimeOffset Considerations

When working with DateTimeOffset (time-zone-aware), the same subtraction works:

csharp
1DateTimeOffset start = DateTimeOffset.UtcNow;
2// ... some operation ...
3DateTimeOffset end = DateTimeOffset.UtcNow;
4
5TimeSpan duration = end - start;

Common Pitfalls

  • Time Zones: Ensure both DateTime values are in the same time zone before subtracting. Mixing DateTimeKind.Local and DateTimeKind.Utc gives misleading results. Use DateTime.UtcNow consistently or convert with ToUniversalTime().
  • Kind Property: Check the DateTimeKind property (Utc, Local, Unspecified). Subtracting Unspecified from Utc does not automatically convert — it just subtracts the raw values.
  • Negative TimeSpan: If start > end, the resulting TimeSpan is negative. Check with TimeSpan.Duration() to get the absolute value: (end - start).Duration().
  • TotalX vs X properties: TimeSpan.Hours returns only the hours component (0-23), while TotalHours returns the total span in hours. For a 25-hour span: .Hours = 1, .TotalHours = 25.
  • DateTime.Now precision: DateTime.Now has limited precision (~15ms on Windows). For sub-millisecond timing, use Stopwatch.

Summary

OperationCode
Time-of-daydateTime.TimeOfDay
Duration between datesendDate - startDate
Manual constructionnew TimeSpan(hours, minutes, seconds)
Add duration to datedateTime.Add(timeSpan)
Precise measurementStopwatch.StartNew() then .Elapsed
  • DateTime.TimeOfDay gives the time-of-day as a TimeSpan
  • Subtracting two DateTime values produces a TimeSpan
  • Always use the same DateTimeKind when calculating durations
  • Use TotalHours/TotalMinutes (not Hours/Minutes) for total duration values
  • Prefer Stopwatch for performance measurement over DateTime subtraction

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.