Skip to content

Instantly share code, notes, and snippets.

@sandcastle
Created November 4, 2015 15:49
Show Gist options
  • Select an option

  • Save sandcastle/fc6a8c69b091444943ca to your computer and use it in GitHub Desktop.

Select an option

Save sandcastle/fc6a8c69b091444943ca to your computer and use it in GitHub Desktop.
Convert dates to friendly text relative to the current time.
public static class DateTimeExtensions
{
static readonly Dictionary<double, Func<TimeSpan, string>> RelativeDateMap;
static DateTimeExtensions() {
RelativeDateMap = new Dictionary<double, Func<TimeSpan, string>> {
{0.75, x => "less than a minute"},
{1.5, x => "about a minute"},
{45, x => string.Format("{0} minutes", Math.Round(Math.Abs(x.TotalMinutes), 0))},
{90, x => "about an hour"},
{60*24, x => string.Format("about {0} hours", Math.Round(Math.Abs(x.TotalHours), 0))},
{60*48, x => "a day"},
{60*24*30, x => string.Format("{0} days", Math.Floor(Math.Abs(x.TotalDays)))},
{60*24*60, x => "about a month"},
{60*24*365, x => string.Format("{0} months", Math.Floor(Math.Abs(x.TotalDays/30)))},
{60*24*365*2, x => "about a year"},
{Double.MaxValue, x => string.Format("{0} years", Math.Floor(Math.Abs(x.TotalDays/365)))}
};
}
public static string ToRelativeDateShort(this DateTime input) {
TimeSpan diff = DateTime.Now.Subtract(input);
double totalMinutes = diff.TotalMinutes;
bool useSuffix = true;
const string suffix = " ago";
const string prefix = "in ";
if (totalMinutes < 0.0) {
totalMinutes = Math.Abs(totalMinutes);
useSuffix = false;
}
if (useSuffix) return RelativeDateMap.First(n => totalMinutes < n.Key).Value(diff) + suffix;
return prefix + RelativeDateMap.First(n => totalMinutes < n.Key).Value(diff);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment