Skip to content

Instantly share code, notes, and snippets.

@jasongaylord
Created November 5, 2018 18:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jasongaylord/afd3e26047cd3170b8fad68cc40eae41 to your computer and use it in GitHub Desktop.
Save jasongaylord/afd3e26047cd3170b8fad68cc40eae41 to your computer and use it in GitHub Desktop.
A DateTime extension to show a friendly date based on the value passed in and DateTime.Now
public static class DateTimeExtensions
{
public static string ToFriendlyDate(this DateTime date)
{
// Calculate the elapsed time
TimeSpan s = DateTime.UtcNow.Subtract(date);
// Get total number of days elapsed.
int dayDiff = (int)s.TotalDays;
// Get total number of seconds elapsed.
int secDiff = (int)s.TotalSeconds;
// If it's the current day...
if (dayDiff == 0)
{
// Less than one minute ago.
if (secDiff < 60)
{
return "just now";
}
// Less than 2 minutes ago.
if (secDiff < 120)
{
return "1 minute ago";
}
// Less than one hour ago.
if (secDiff < 3600)
{
return string.Format("{0} minutes ago",
Math.Floor((double)secDiff / 60));
}
// Less than 2 hours ago.
if (secDiff < 7200)
{
return "1 hour ago";
}
// Less than one day ago.
if (secDiff < 86400)
{
return string.Format("{0} hours ago",
Math.Floor((double)secDiff / 3600));
}
}
// Everything else...
if (dayDiff == 1)
{
return "yesterday";
}
if (dayDiff < 7)
{
return string.Format("{0} days ago",
dayDiff);
}
if (dayDiff < 31)
{
return string.Format("{0} weeks ago",
Math.Ceiling((double)dayDiff / 7));
}
return date.ToString();
}
}
@Calabonga
Copy link

Thanks for sharing. Can you implement multi-language functionality?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment