Change DateTime To A Friendly Name

Here is a simple extension method to convert a DateTime type to a friendly name like "Today" or "Yesterday," as you see in some file browsers.

  1. public static string ToFriendlyDateString(this DateTime input)  
  2. {  
  3.     var formattedDate = string.Empty;  
  4.     if (input.Date == DateTime.Today)  
  5.     {  
  6.         formattedDate = nameof(DateTime.Today);  
  7.     }  
  8.     else  
  9.     {  
  10.         formattedDate = input.Date == DateTime.Today.AddDays(-1) ? "Yesterday" :   
  11.                         input.Date > DateTime.Today.AddDays(-6) ?   
  12.                         input.ToString("dddd").ToString() :   
  13.                         input.ToString(CultureInfo.CurrentCulture.DateTimeFormat.LongDatePattern,   
  14.                                        CultureInfo.CurrentCulture);  
  15.     }  
  16.     formattedDate += " @ " + input.ToString(CultureInfo.CurrentCulture.DateTimeFormat.LongTimePattern,  
  17.                                             CultureInfo.CurrentCulture).ToLower();  
  18.     return formattedDate;  
  19. }  
You can find this code and lots more in my dotNetTips.Utility open source project.
McCarter Consulting
Software architecture, code & app performance, code quality, Microsoft .NET & mentoring. Available!