How to Calculate relative time in C#?

In C#, calculating relative time (like "2 hours ago") can be done in two main ways: using a ready-made NuGet package for simplicity and localization, or writing a custom helper method for full control and no dependencies.

Option 1: Use a NuGet Package

If you want a robust solution that handles multiple languages and is easy to use, a library like Meziantou.Framework.RelativeDate is a great choice.

Key Features:

→Easy to Use: Just pass a date to RelativeDate.Get() and call ToString().
→Culture Aware: It automatically uses the current UI culture for formatting, so you get "5 minutes ago" in English or "il y a 5 minutes" in French without extra work.
→Handles Time Zones: It requires DateTime values to be explicitly Utc or Local to avoid ambiguity, throwing an exception for Unspecified kinds.
→Testable: It supports injecting a TimeProvider, making it easy to write unit tests with a FakeTimeProvider.

Example Usage:

using Meziantou.Framework;
using System.Globalization;

DateTime pastDate = DateTime.UtcNow.AddMinutes(-5);
string result = RelativeDate.Get(pastDate).ToString();
// result (in en-US): “5 minutes ago”

Option 2: Write a Custom Helper Method

If you prefer not to add a dependency, you can implement a simple helper method yourself. This gives you complete control over the logic and output strings.

The core idea is to calculate the TimeSpan between the target date and now, then use a series of thresholds to determine the appropriate string.

Example Implementation: This is a common approach adapted from community solutions.

public static class RelativeTimeHelper
{
   public static string GetRelativeTime(DateTime dateTime)
   {
       var timeSpan = DateTime.Now - dateTime;
       var delta = Math.Abs(timeSpan.TotalSeconds);       if (delta < 60) // Less than a minute
           return timeSpan.Seconds <= 1 ? "just now" : $"{timeSpan.Seconds} seconds ago";
       if (delta < 120) // Less than 2 minutes
           return "a minute ago";
       if (delta < 2700) // Less than 45 minutes
           return $"{timeSpan.Minutes} minutes ago";
       if (delta < 5400) // Less than 90 minutes
           return "an hour ago";
       if (delta < 86400) // Less than 24 hours
           return $"{timeSpan.Hours} hours ago";
       if (delta < 172800) // Less than 48 hours
           return "yesterday";
       if (delta < 2592000) // Less than 30 days
           return $"{timeSpan.Days} days ago";
       if (delta < 31536000) // Less than 1 year
       {
           int months = Convert.ToInt32(Math.Floor((double)timeSpan.Days / 30));
           return months <= 1 ? "a month ago" : $"{months} months ago";
       }

       int years = Convert.ToInt32(Math.Floor((double)timeSpan.Days / 365));
       return years <= 1 ? "a year ago" : $"{years} years ago";
   }
}

Key Considerations

→Time Zones: Always be mindful of DateTime.Kind. For accuracy, it is best practice to store and compare dates in UTC. If you re using a custom method, consider using DateTime.UtcNow and ensuring your input date is also UTC to avoid local time zone skewing the result.
→Precision: Simple custom methods often use approximations (e.g., 30 days for a month, 365 days for a year). This is usually fine for relative displays like "a month ago" but not for precise calculations.

25 Views