public static string Relative(this HtmlHelper helper, DateTime date) { var span = DateTime.Now - date; var minutes = span.TotalMinutes; if (minutes < 0.75) return "less than a minute ago"; else if (minutes < 1.5) return "a minute ago"; else if (minutes < 45) return string.Format("{0} minutes ago", Math.Round(minutes)); else if (minutes < 90) return "an hour ago"; else if (minutes < 1440) return string.Format("{0} hours ago", Math.Round(Math.Abs(span.TotalHours))); else if (minutes < 2880) return "a day ago"; else if (minutes < 43200) return string.Format("{0} days ago", Math.Floor(Math.Abs(span.TotalDays))); else if (minutes < 86400) return "a month ago"; else if (minutes < 525600) return string.Format("{0} months ago", Math.Floor(Math.Abs(span.TotalDays / 30))); return string.Format("{0} years ago", Math.Floor(Math.Abs(span.TotalDays / 365))); }
Now it is very easy in your view code to add pretty dates whenever you need them.
No comments:
Post a Comment