Created
November 5, 2018 18:38
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for sharing. Can you implement multi-language functionality?