Skip to content

Instantly share code, notes, and snippets.

@Rychu-Pawel
Created April 29, 2021 08:37
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 Rychu-Pawel/fefb89e21b764e97e4993ff517ff0129 to your computer and use it in GitHub Desktop.
Save Rychu-Pawel/fefb89e21b764e97e4993ff517ff0129 to your computer and use it in GitHub Desktop.
TimeSpan Readable Ago String
public static class TimeSpanExtensions
{
// Inspired by @Peter answear from https://stackoverflow.com/questions/842057/how-do-i-convert-a-timespan-to-a-formatted-string
public static string ToReadableAgoString(this TimeSpan span, double justNowSecondsThreshold)
{
if (span.TotalSeconds < justNowSecondsThreshold)
return "just now";
return span switch
{
TimeSpan { TotalDays: > 1 } => string.Format("{0:0} day{1} ago", span.Days, span.Days == 1 ? string.Empty : "s"),
TimeSpan { TotalHours: > 1 } => string.Format("{0:0} hour{1} ago", span.Hours, span.Hours == 1 ? string.Empty : "s"),
TimeSpan { TotalMinutes: > 1 } => string.Format("{0:0} minute{1} ago", span.Minutes, span.Minutes == 1 ? string.Empty : "s"),
_ => string.Format("{0:0} second{1} ago", span.Seconds, span.Seconds == 1 ? string.Empty : "s")
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment