Skip to content

Instantly share code, notes, and snippets.

@sahgilbert
Created May 22, 2019 13:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sahgilbert/b07df7a523b77d47899258318cdcc439 to your computer and use it in GitHub Desktop.
Save sahgilbert/b07df7a523b77d47899258318cdcc439 to your computer and use it in GitHub Desktop.
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