Saturday, March 13, 2010

Turning a DateTime into a Friendly String

Over at http://www.primershee.com/Forum.aspx, the date column shows a friendly string version of when each post was last updated.  I used the following extension method…

        public static string ToFriendlyString(this DateTime date)
{
if (date.DayOfYear < DateTime.Now.DayOfYear)
return date.ToString();
else
{
TimeSpan span = DateTime.Now.Subtract(date);
if (span.Hours >= 1)
return span.Hours + " Hours Ago";
else if (span.Minutes >= 1)
return span.Minutes + " Minutes Ago";
else return span.Seconds + " Seconds Ago";
}
}

1 comment:

  1. i changed:

    if (date.DayOfYear < DateTime.Now.DayOfYear)

    to

    if (date.DayOfYear < DateTime.Now.DayOfYear && date.Year == DateTime.Now.Year)

    so it works when the dates are on same day of year but different year.

    ReplyDelete