Skip to content

Instantly share code, notes, and snippets.

@ncelico
Created February 4, 2015 14:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ncelico/7f5eda9137ca668cf498 to your computer and use it in GitHub Desktop.
Save ncelico/7f5eda9137ca668cf498 to your computer and use it in GitHub Desktop.
Pretty Date formatting Extension Method for DateTime in C#. Mostly inspired by http://www.dotnetperls.com/pretty-date
using System;
namespace YourCompany.Extension
{
public static class PrettyDate
{
public static String GetPrettyDate(this DateTime date)
{
// 1.
// Get time span elapsed since the date.
var s = DateTime.Now.Subtract(date);
// 2.
// Get total number of days elapsed.
var dayDiff = (int)s.TotalDays;
// 3.
// Get total number of seconds elapsed.
var secDiff = (int)s.TotalSeconds;
// 4.
// Don't allow out of range values.
if (dayDiff < 0)
{
return null;
}
// 5.
// Handle same-day times.
if (dayDiff == 0)
{
// A.
// Less than one minute ago.
if (secDiff < 60)
{
return "just now";
}
// B.
// Less than 2 minutes ago.
if (secDiff < 120)
{
return "1m ago";
}
// C.
// Less than one hour ago.
if (secDiff < 3600)
{
return string.Format("{0}m ago",
Math.Floor((double)secDiff / 60));
}
// D.
// Less than 2 hours ago.
if (secDiff < 7200)
{
return "1h ago";
}
// E.
// Less than one day ago.
if (secDiff < 86400)
{
return string.Format("{0}h ago",
Math.Floor((double)secDiff / 3600));
}
}
// 6.
// Handle previous days.
if (dayDiff == 1)
{
return "yesterday";
}
if (dayDiff < 7)
{
return string.Format("{0}d ago",
dayDiff);
}
if (dayDiff < 91)
{
return string.Format("{0}w ago",
Math.Ceiling((double)dayDiff / 7));
}
// 7.
// Handle very old values
return date.ToShortDateString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment