Convert DateTime to TimeSpan
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
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:
Calculating Duration Between Two DateTimes
Subtracting two DateTime values produces a TimeSpan:
Multi-Day Durations
TimeSpan from DateTime Components
Create a TimeSpan manually from a DateTime's components:
Elapsed Time Since a Reference Point
Calculate time elapsed since midnight, epoch, or any reference:
Adding TimeSpan to DateTime
The reverse operation — adding a duration to a point in time:
Formatting TimeSpan
Using Stopwatch for Precise Timing
For measuring code execution time, prefer Stopwatch over DateTime subtraction:
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:
Common Pitfalls
- Time Zones: Ensure both
DateTimevalues are in the same time zone before subtracting. MixingDateTimeKind.LocalandDateTimeKind.Utcgives misleading results. UseDateTime.UtcNowconsistently or convert withToUniversalTime(). - Kind Property: Check the
DateTimeKindproperty (Utc,Local,Unspecified). SubtractingUnspecifiedfromUtcdoes not automatically convert — it just subtracts the raw values. - Negative TimeSpan: If
start > end, the resultingTimeSpanis negative. Check withTimeSpan.Duration()to get the absolute value:(end - start).Duration(). - TotalX vs X properties:
TimeSpan.Hoursreturns only the hours component (0-23), whileTotalHoursreturns the total span in hours. For a 25-hour span:.Hours= 1,.TotalHours= 25. - DateTime.Now precision:
DateTime.Nowhas limited precision (~15ms on Windows). For sub-millisecond timing, useStopwatch.
Summary
| Operation | Code |
| Time-of-day | dateTime.TimeOfDay |
| Duration between dates | endDate - startDate |
| Manual construction | new TimeSpan(hours, minutes, seconds) |
| Add duration to date | dateTime.Add(timeSpan) |
| Precise measurement | Stopwatch.StartNew() then .Elapsed |
DateTime.TimeOfDaygives the time-of-day as aTimeSpan- Subtracting two
DateTimevalues produces aTimeSpan - Always use the same
DateTimeKindwhen calculating durations - Use
TotalHours/TotalMinutes(notHours/Minutes) for total duration values - Prefer
Stopwatchfor performance measurement overDateTimesubtraction

