When you read a value from database that has a timestamp. lets say 2016/29/12T08:00 - when you execute the code now i.e. 10PM - the output expect as "12 hours ago".
Where the time will specify the exact duration of value fetched from current time.
Where the time will specify the exact duration of value fetched from current time.
public static string ToRelativeDate(this DateTime dateTime)
{
var timeSpan = DateTime.Now - dateTime;
if (timeSpan <= TimeSpan.FromSeconds(60))
return string.Format("{0} seconds ago", timeSpan.Seconds);
if (timeSpan <= TimeSpan.FromMinutes(60))
return timeSpan.Minutes > 1 ? String.Format("about {0} minutes ago", timeSpan.Minutes) : "about a minute ago";
if (timeSpan <= TimeSpan.FromHours(24))
return timeSpan.Hours > 1 ? String.Format("about {0} hours ago", timeSpan.Hours) : "about an hour ago";
if (timeSpan <= TimeSpan.FromDays(30))
return timeSpan.Days > 1 ? String.Format("about {0} days ago", timeSpan.Days) : "yesterday";
if (timeSpan <= TimeSpan.FromDays(365))
return timeSpan.Days > 30 ? String.Format("about {0} months ago", timeSpan.Days / 30) : "about a month ago";
return timeSpan.Days > 365 ? String.Format("about {0} years ago", timeSpan.Days / 365) : "about a year ago";
}