Created
May 22, 2019 13:48
-
-
Save sahgilbert/b07df7a523b77d47899258318cdcc439 to your computer and use it in GitHub Desktop.
DateTime Extension Methods - C# .Net Core
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
using System; | |
namespace SimonGilbert.Blog | |
{ | |
public static class DateTimeExtensions | |
{ | |
public static string ToRelativeDate(this DateTime dateTime) | |
{ | |
var timeSpan = DateTime.Now - dateTime; | |
if (timeSpan <= TimeSpan.FromSeconds(60)) | |
return $"{timeSpan.Seconds} seconds ago"; | |
if (timeSpan <= TimeSpan.FromMinutes(60)) | |
return timeSpan.Minutes > 1 ? $"{timeSpan.Minutes} minutes ago" : "a minute ago"; | |
if (timeSpan <= TimeSpan.FromHours(24)) | |
return timeSpan.Hours > 1 ? $"{timeSpan.Hours} hours ago" : "an hour ago"; | |
if (timeSpan <= TimeSpan.FromDays(30)) | |
return timeSpan.Days > 1 ? $"{timeSpan.Days} days ago" : "yesterday"; | |
if (timeSpan <= TimeSpan.FromDays(365)) | |
return timeSpan.Days > 30 ? $"{timeSpan.Days / 30} months ago" : "a month ago"; | |
return timeSpan.Days > 365 ? $"{timeSpan.Days / 365} years ago" : "a year ago"; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment