ToFriendlyDateString
namespace Utils { public static class Extensions { public static string ToFriendlyDateString(this DateTime Date) { string FormattedDate = ""; if (Date.Date == DateTime.Today) { FormattedDate = "Today"; } else if (Date.Date == DateTime.Today.AddDays(-1)) { FormattedDate = "Yesterday"; } else if (Date.Date > DateTime.Today.AddDays(-6)) { // *** Show the Day of the week FormattedDate = Date.ToString("dddd").ToString(); } else { FormattedDate = Date.ToString("MMMM dd, yyyy"); } //append the time portion to the output FormattedDate += " @ " + Date.ToString("t").ToLower(); return FormattedDate; } } }Example:
using Utils; ...... DateTime dt = new DateTime(2008, 2, 10, 8, 48, 20); Console.WriteLine(dt.ToFriendlyDateString());
Description
The idea behind the ToFriendlyDateString() method is representing dates in a user friendly way. For example, when displaying a news article on a webpage, you might want articles that were published one day ago to have their publish dates represented as "yesterday at 12:30 PM". Or if the article was publish today, show the date as "Today, 3:33 PM".
Details
- Author: jaycent
- Submitted on: 12-2-2008 22:21:15
- Language: C#
- Type: System.DateTime
- Views: 3544
Double click on the code to select all.