Convert DateTime to TimeSpan
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
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
Related reading
- Convert Dictionarystring, object To Anonymous Object?
- Convert double to float by cast or Convert.ToSingle?
- Convert Enum to String
- Convert existing C synchronous method to asynchronous with async/await?
- Convert int to a bit array in .NET
- Convert JObject into Dictionarystring, object. Is it possible?
- Convert ListT to ObservableCollectionT in WP7
- Convert .Net Core to .Net Framework

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack 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.