Return to Snippet

Revision: 46295
at May 17, 2011 01:40 by Maelstrom


Initial Code
public static string PrettyDate(String TimeSubmitted)
{
	// accepts standard DateTime: 5/12/2011 2:36:00 PM 
	// returns: "# month(s)/week(s)/day(s)/hour(s)/minute(s)/second(s)) ago"
	string prettyDate = TimeSubmitted;

	DateTime SubmittedDate = DateTime.Parse(TimeSubmitted);
	DateTime Now = DateTime.Now;
	TimeSpan Diff = Now - SubmittedDate;

	if (Diff.Seconds <= 0)
	{
		prettyDate = TimeSubmitted;
	} 
	else if (Diff.Days > 30)
	{
		prettyDate = Diff.Days / 30 + " month" + (Diff.Days / 30 >= 2 ? "s " : " ") + "ago";
	}
	else if (Diff.Days > 7)
	{
		prettyDate = Diff.Days / 7 + " week" + (Diff.Days / 7 >= 2 ? "s " : " ") + "ago";
	}
	else if (Diff.Days >= 1)
	{
		prettyDate = Diff.Days + " day" + (Diff.Days >= 2 ? "s " : " ") + "ago";
	}
	else if (Diff.Hours >= 1)
	{
		prettyDate = Diff.Hours + " hour" + (Diff.Hours >= 2 ? "s " : " ") + "ago";
	}
	else if (Diff.Minutes >= 1)
	{
		prettyDate = Diff.Minutes + " minute" + (Diff.Minutes >= 2 ? "s " : " ") + "ago";
	}
	else
	{
		prettyDate = Diff.Seconds + " second" + (Diff.Seconds >= 2 ? "s " : " ") + "ago";
	}
	return prettyDate;
}

Initial URL
prettydate

Initial Description
A simple C# function to take a standard DateTime and convert it to a pretty string saying how many seconds/minutes/days/weeks/months ago the date was, it doesn't return an actual date, but that wouldn't be hard to change the month/week/day section to return a formatted date instead of the string currently returned.

Initial Title
Pretty Date (Facebook/Twitter style) - X Month(s)/Week(s)/Day(s)/Hour(s)/Minute(s)/Second(s) ago

Initial Tags
date, facebook

Initial Language
C#