Last active
December 14, 2015 16:39
-
-
Save JPaulDuncan/b753f110ffc9613249ce to your computer and use it in GitHub Desktop.
Generates a date description relative the current date.
This file contains hidden or 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 string ToRelativeDateString(this DateTime date) | |
| { | |
| return DateTimeExtensions.GetRelativeDateValue(date, DateTime.Now); | |
| } | |
| public static string ToRelativeDateStringUtc(this DateTime date) | |
| { | |
| return DateTimeExtensions.GetRelativeDateValue(date, DateTime.UtcNow); | |
| } | |
| private static string GetRelativeDateValue(DateTime date, DateTime comparedTo) | |
| { | |
| TimeSpan timeSpan = comparedTo.Subtract(date); | |
| if (timeSpan.TotalDays >= 365.0) | |
| { | |
| return "on " + date.ToString("MMMM d, yyyy"); | |
| } | |
| if (timeSpan.TotalDays >= 7.0) | |
| { | |
| return "on " + date.ToString("MMMM d"); | |
| } | |
| if (timeSpan.TotalDays > 1.0) | |
| { | |
| return string.Format("{0:N0} days ago", timeSpan.TotalDays); | |
| } | |
| if (timeSpan.TotalDays == 1.0) | |
| { | |
| return "yesterday"; | |
| } | |
| if (timeSpan.TotalHours >= 2.0) | |
| { | |
| return string.Format("{0:N0} hours ago", timeSpan.TotalHours); | |
| } | |
| if (timeSpan.TotalMinutes >= 60.0) | |
| { | |
| return "more than an hour ago"; | |
| } | |
| if (timeSpan.TotalMinutes >= 5.0) | |
| { | |
| return string.Format("{0:N0} minutes ago", timeSpan.TotalMinutes); | |
| } | |
| if (timeSpan.TotalMinutes >= 1.0) | |
| { | |
| return "a few minutes ago"; | |
| } | |
| return "less than a minute ago"; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment