ExtensionMethod.NET Home of 819 C#, Visual Basic, F# and Javascript extension methods

ToFriendlyDateString

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".

Source

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());

Author: jaycent

Submitted on: 12 feb 2008

Language: C#

Type: System.DateTime

Views: 4101