Creating Twitter-esque Relative Dates in C#
Recently, I was asked if we could have “relative dates like on Twitter” for a project. With a great deal surprise (they knew what Twitter was??), I thought about it for a second and said, “Sure, why not”
It’s just a machine—how difficult can it be? Well, actually, not very difficult in C#.
Here’s what I came up with to handle everything from seconds to years. It’s not really pretty and, honestly, may not be that efficient (I haven’t ran it with tens of thouasnds of dates at once and benchmarked it), but it works well and is convenient as an extension method.
/// Converts the specified DateTime to its relative date.
/// <param name=”dateTime”>The DateTime to convert.</param>
/// <returns>A string value based on the relative date
/// of the datetime as compared to the current date.</returns>
public static string ToRelativeDate(this DateTime dateTime)
var timeSpan = DateTime.Now – dateTime;
// span is less than or equal to 60 seconds, measure in seconds.
if (timeSpan <= TimeSpan.FromSeconds(60))
return timeSpan.Seconds + ” seconds ago”;
// span is less than or equal to 60 minutes, measure in minutes.
if (timeSpan <= TimeSpan.FromMinutes(60))
return timeSpan.Minutes > 1
? “about “ + timeSpan.Minutes + ” minutes ago”
: “about a minute ago”;
// span is less than or equal to 24 hours, measure in hours.
if (timeSpan <= TimeSpan.FromHours(24))
return timeSpan.Hours > 1
? “about “ + timeSpan.Hours + ” hours ago”
: “about an hour ago”;
// span is less than or equal to 30 days (1 month), measure in days.
if (timeSpan <= TimeSpan.FromDays(30))
return timeSpan.Days > 1
? “about “ + timeSpan.Days + ” days ago”
: “about a day ago”;
// span is less than or equal to 365 days (1 year), measure in months.
if (timeSpan <= TimeSpan.FromDays(365))
return timeSpan.Days > 30
? “about “ + timeSpan.Days / 30 + ” months ago”
: “about a month ago”;
// span is greater than 365 days (1 year), measure in years.
return timeSpan.Days > 365
? “about “ + timeSpan.Days / 365 + ” years ago”
: “about a year ago”;
Friday, September 18, 1981 :: about 26 years ago
Monday, August 06, 2001 :: about 7 years ago
Notice that I’m not accounting for leap years—every year is 365 instead of 366 every fourth year [year calculations are fun!]. Given a certain number of years, you’d eventually be a few days, then weeks, then months ahead. You could accomodate for this in the timeSpan, but for a ‘relative date’—does that add value (unless wanting the relative date of 10,000 years ago and it shows up as 10,001.