/ Published in: C#
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.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
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; }
URL: prettydate