DateTime Extension Methods - C# .Net Core
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