What is the best library for displaying relative dates (eg: 20 minutes ago) for ASP.NET MVC using in C#?
Asked
Active
Viewed 3,459 times
5
-
possible duplicate of [How do I calculate relative time?](http://stackoverflow.com/questions/11/how-do-i-calculate-relative-time) – Gabe Moothart Sep 10 '10 at 15:49
-
For .Net core Install-Package ChronicNetCore. https://www.nuget.org/packages/ChronicNetCore/ – Michael Freidgeim May 10 '22 at 20:34
4 Answers
22
You don't need a library when a simple extension method can do it. This is an extension method that I have used:
public static string TimeAgo(this DateTime date)
{
TimeSpan timeSince = DateTime.Now.Subtract(date);
if (timeSince.TotalMilliseconds < 1) return "not yet";
if (timeSince.TotalMinutes < 1) return "just now";
if (timeSince.TotalMinutes < 2) return "1 minute ago";
if (timeSince.TotalMinutes < 60) return string.Format("{0} minutes ago", timeSince.Minutes);
if (timeSince.TotalMinutes < 120) return "1 hour ago";
if (timeSince.TotalHours < 24) return string.Format("{0} hours ago", timeSince.Hours);
if (timeSince.TotalDays < 2) return "yesterday";
if (timeSince.TotalDays < 7) return string.Format("{0} days ago", timeSince.Days);
if (timeSince.TotalDays < 14) return "last week";
if (timeSince.TotalDays < 21) return "2 weeks ago";
if (timeSince.TotalDays < 28) return "3 weeks ago";
if (timeSince.TotalDays < 60) return "last month";
if (timeSince.TotalDays < 365) return string.Format("{0} months ago", Math.Round(timeSince.TotalDays / 30));
if (timeSince.TotalDays < 730) return "last year"; //last but not least...
return string.Format("{0} years ago", Math.Round(timeSince.TotalDays / 365));
}

Kelsey
- 47,246
- 16
- 124
- 162
-
An anonymous user submitted a suggested edit with the title *Kelsey, can you fix your code for the following: When timeSince.TotalDays == 1.9243, it's returning "1 days ago"*, suggesting a bug on the "yesterday" line. It should be a comment rather than an edit, but I don't think the user is able to post comments. – Keith Thompson Jan 02 '12 at 03:53
6
How about this? But this is jQuery plugin. not c#.

takepara
- 10,413
- 3
- 34
- 31
-
1I'd personally use this option, it does the heavy lifting on the client instead of the server which would be important for sites with a lot of traffic. You can't cache "minute ago" type information. – John Jan 24 '12 at 21:20
1
Humanizer is a fantastic library for this. It is on nuget and includes lots of other great conversions for strings and enums in addition to dates.

viggity
- 15,039
- 7
- 88
- 96
-
Humanizer has bugs with TimeSpan. See [here](https://github.com/Humanizr/Humanizer/issues/583) – redwards510 Dec 08 '16 at 19:06
0
I don't know of any established library that exists for this but http://tiredblogger.wordpress.com/2008/08/21/creating-twitter-esque-relative-dates-in-c/ should get you started.

Michael Shimmins
- 19,961
- 7
- 57
- 90