Skip to content

Instantly share code, notes, and snippets.

@JPaulDuncan
Last active December 14, 2015 16:39
Show Gist options
  • Select an option

  • Save JPaulDuncan/b753f110ffc9613249ce to your computer and use it in GitHub Desktop.

Select an option

Save JPaulDuncan/b753f110ffc9613249ce to your computer and use it in GitHub Desktop.
Generates a date description relative the current date.
public static string ToRelativeDateString(this DateTime date)
{
return DateTimeExtensions.GetRelativeDateValue(date, DateTime.Now);
}
public static string ToRelativeDateStringUtc(this DateTime date)
{
return DateTimeExtensions.GetRelativeDateValue(date, DateTime.UtcNow);
}
private static string GetRelativeDateValue(DateTime date, DateTime comparedTo)
{
TimeSpan timeSpan = comparedTo.Subtract(date);
if (timeSpan.TotalDays >= 365.0)
{
return "on " + date.ToString("MMMM d, yyyy");
}
if (timeSpan.TotalDays >= 7.0)
{
return "on " + date.ToString("MMMM d");
}
if (timeSpan.TotalDays > 1.0)
{
return string.Format("{0:N0} days ago", timeSpan.TotalDays);
}
if (timeSpan.TotalDays == 1.0)
{
return "yesterday";
}
if (timeSpan.TotalHours >= 2.0)
{
return string.Format("{0:N0} hours ago", timeSpan.TotalHours);
}
if (timeSpan.TotalMinutes >= 60.0)
{
return "more than an hour ago";
}
if (timeSpan.TotalMinutes >= 5.0)
{
return string.Format("{0:N0} minutes ago", timeSpan.TotalMinutes);
}
if (timeSpan.TotalMinutes >= 1.0)
{
return "a few minutes ago";
}
return "less than a minute ago";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment