After looking on the net and not being completely satisified with the solutions out there on formatting to this style, I headed over to trusty stackoverflow.com and did really like the one Jeff Atwood and the team use on stackoverflow.com, until I saw the more concise version down below.
Mind you this is the one I initially tried, and teared my hair out as when doing some AddMinutes(-40) tests it was returning things like ’40 hours ago’.
However Michael Wolfenden pointed out an excellent routine using Lambda syntax as well, very elegant. (I wrapped it into a handy ASP.NET Html Helper Extension for convenience).
///
/// Format date/time object into html representation of 'relative time' format, eg. "5 seconds ago".
///
///
///
///
public static string FormatDateTimeRelative(this HtmlHelper htmlHelper, DateTime? value)
{
if (value.HasValue)
{
// As suggested on stackoverflow.com and found to be the most comprehensive method.
// Jeff Atwood's method is nice, but this is more concise.
// http://stackoverflow.com/questions/11/how-do-i-calculate-relative-time
TimeSpan oSpan = DateTime.Now.Subtract(value.Value);
double TotalMinutes = oSpan.TotalMinutes;
string Suffix = " ago";
if (TotalMinutes < 0.0)
{
TotalMinutes = Math.Abs(TotalMinutes);
Suffix = " from now";
}
Dictionary aValue = new Dictionary();
aValue.Add(0.75, () => "less than a minute");
aValue.Add(1.5, () => "about a minute");
aValue.Add(45, () => string.Format("{0} minutes", Math.Round(TotalMinutes)));
aValue.Add(90, () => "about an hour");
aValue.Add(1440, () => string.Format("about {0} hours", Math.Round(Math.Abs(oSpan.TotalHours)))); // 60 * 24
aValue.Add(2880, () => "a day"); // 60 * 48
aValue.Add(43200, () => string.Format("{0} days", Math.Floor(Math.Abs(oSpan.TotalDays)))); // 60 * 24 * 30
aValue.Add(86400, () => "about a month"); // 60 * 24 * 60
aValue.Add(525600, () => string.Format("{0} months", Math.Floor(Math.Abs(oSpan.TotalDays / 30)))); // 60 * 24 * 365
aValue.Add(1051200, () => "about a year"); // 60 * 24 * 365 * 2
aValue.Add(double.MaxValue, () => string.Format("{0} years", Math.Floor(Math.Abs(oSpan.TotalDays / 365))));
return aValue.First(n => TotalMinutes < n.Key).Value.Invoke() + Suffix;
}
return string.Empty;
}
Here is the original post on http://stackoverflow.com/questions/11/how-do-i-calculate-relative-time
But if you are looking for something a little more dynamic and wish to have DOM updates on the fly while preserving your original timestamp in yyyy:MM:dd HH:mm:ss on the page or whatever, check the jquery.timeago plugin also suggested on that post.
Very cool.
Post a Comment