Have you ever wondered how some sites were able to show the bottom of each post, a formatted date (pretty date) which estimates the number of days, months or years between the publication of the post and today? e.g. "posted 5 weeks ago"
This snippet will allow you to do this easily!
You can improve this code by adding, for example, a dictionary of resources for the different languages of your application or website.
Any comments are welcome!
private const string secondsAgo = "{0} seconds ago";
private const string minuteAgo = "{0} minute ago";
private const string minutesAgo = "{0} minutes ago";
private const string hourAgo = "{0} hour ago";
private const string hoursAgo = "{0} hours ago";
private const string dayAgo = "{0} day ago";
private const string daysAgo = "{0} days ago";
private const string weekAgo = "{0} week ago";
private const string weeksAgo = "{0} weeks ago";
private const string monthAgo = "{0} month ago";
private const string monthsAgo = "{0} months ago";
public static string GetPrettyDate(DateTime date) {
var timeDifference = DateTime.Now.Subtract(date);
if (timeDifference.TotalSeconds < 60) {
return String.Format(secondsAgo, Math.Floor(timeDifference.TotalSeconds));
}
if (timeDifference.TotalMinutes < 60) {
return String.Format(timeDifference.TotalMinutes < 2
? minuteAgo
: minutesAgo, Math.Floor(timeDifference.TotalMinutes));
}
if (timeDifference.TotalHours < 24) {
return String.Format(timeDifference.TotalHours < 2
? hourAgo
: hoursAgo, Math.Floor(timeDifference.TotalHours));
}
if (timeDifference.TotalDays < 7) {
return String.Format(timeDifference.TotalDays < 2
? dayAgo
: daysAgo, Math.Floor(timeDifference.TotalDays));
}
if (timeDifference.TotalDays < 30) {
return String.Format(timeDifference.TotalDays < 14
? weekAgo
: weeksAgo, Math.Floor(timeDifference.TotalDays / 7));
}
if (timeDifference.TotalDays < 180) {
return String.Format(timeDifference.TotalDays < 60
? monthAgo
: monthsAgo, Math.Floor(timeDifference.TotalDays / 30));
}
return date.ToShortDateString();
}