Created
April 29, 2021 08:37
-
-
Save Rychu-Pawel/fefb89e21b764e97e4993ff517ff0129 to your computer and use it in GitHub Desktop.
TimeSpan Readable Ago String
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
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