Calculate relative time in C#
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Calculating relative time in C# means converting a DateTime or DateTimeOffset into a human-readable string like "5 minutes ago", "2 days ago", or "just now." This is common in social media feeds, comment timestamps, and notification systems. The core approach uses TimeSpan to compute the difference between the target time and the current time, then selects the appropriate unit (seconds, minutes, hours, days, months, years) based on the magnitude of the difference.
Basic Implementation
Supporting Future Dates
Extend the function to handle both past and future timestamps:
Using DateTimeOffset for Time Zones
DateTimeOffset includes timezone information, making comparisons across time zones correct. Prefer DateTimeOffset over DateTime when dealing with user-submitted timestamps.
Extension Method Pattern
Using Humanizer Library
The Humanizer NuGet package handles relative time with localization support:
Humanizer handles edge cases, pluralization, and localization that a hand-rolled solution would need to implement manually.
Formatting for Display
This pattern (used by Twitter, Facebook, and other platforms) shows relative time for recent events and absolute dates for older ones.
Common Pitfalls
- Using
DateTime.Nowinstead ofDateTime.UtcNow:DateTime.Nowuses the server's local time zone. If the server and client are in different zones, the relative time is wrong. Always compute with UTC and convert for display. - Integer division for months and years: Dividing
TotalDaysby 30 or 365 is approximate. February has 28-29 days, and months vary from 28-31. For precise month/year calculations, compare theDateTimeproperties directly (e.g., year and month fields). - Not handling negative TimeSpan: If the input time is in the future,
TimeSpanis negative. Without a check, you get "-5 minutes ago." Either reject future dates or handle them with "from now" wording. - Forgetting to handle the singular form: "1 minutes ago" looks wrong. Always check for the singular case and use "1 minute ago" instead. The Humanizer library handles this automatically.
- Not updating displayed timestamps: In SPAs and real-time apps, relative timestamps become stale. A "5 minutes ago" label never updates to "10 minutes ago" unless you refresh. Use a timer to periodically recalculate displayed timestamps.
Summary
- Use
TimeSpanto compute the difference between now and the targetDateTime - Check thresholds in order (seconds, minutes, hours, days, months, years) and return the appropriate string
- Always use
DateTime.UtcNoworDateTimeOffset.UtcNowfor correct cross-timezone behavior - Use the Humanizer NuGet package for production-grade relative time with localization and pluralization
- Combine relative time for recent events with absolute dates for older events for the best user experience
Related reading
- Call and Callvirt
- Call multiple stored procedures using Async/Await and EntityFramework
- Call parent method from child class c
- Calling a C async WebMethod using jQuery's .ajax hangs endlessly
- Calling a function from a string in C
- Calling an async method using a Task.Run seems wrong?
- Calling Async Method from Sync Method
- Calling async method from sync method is ASP .NET web api - issue

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.