🔨 Add meaningful implementation of Ago()

Ago() now returns a human-readable string instead of a DateTime
This commit is contained in:
Oliver Booth 2019-11-16 02:10:16 +00:00
parent 1712dbaa02
commit cd04c1b66f
No known key found for this signature in database
GPG Key ID: 4B0992B2602C3778
1 changed files with 37 additions and 6 deletions

View File

@ -14,11 +14,42 @@
/// <summary> /// <summary>
/// Calculates how long ago a specified <see cref="TimeSpan"/> was. /// Calculates how long ago a specified <see cref="TimeSpan"/> was.
/// </summary> /// </summary>
/// <param name="span">The <see cref="TimeSpan"/>.</param> /// <param name="span">The <see cref="TimeSpan"/>. Defaults to <see langword="false"/>.</param>
/// <param name="utc">Optional. Whether or not to use <see cref="DateTime.UtcNow"/> instead of <see cref="DateTime.Now"/>. /// <returns>Returns a human-readable <see cref="String"/> describing how long ago <paramref name="span"/>
/// Defaults to <see langword="false"/>.</param> /// represents from now.</returns>
/// <returns>Returns a <see cref="DateTime"/>.</returns> public static string Ago(this TimeSpan span)
public static DateTime Ago(this TimeSpan span, bool utc = false) => {
(utc ? DateTime.UtcNow : DateTime.Now) - span; if (span < TimeSpan.FromSeconds(60))
{
return $"{span.Seconds} seconds ago";
}
if (span < TimeSpan.FromMinutes(60))
{
return span.Minutes > 1 ? $"about {span.Minutes} minutes ago" : "about a minute ago";
}
if (span < TimeSpan.FromHours(24))
{
return span.Hours > 1 ? $"about {span.Hours} hours ago" : "about an hour ago";
}
if (span <= TimeSpan.FromDays(7))
{
return span.Days > 1 ? $"about {span.Days} days ago" : "yesterday";
}
if (span < TimeSpan.FromDays(30))
{
return $"about {span.Days} days ago";
}
if (span < TimeSpan.FromDays(365))
{
return span.Days > 30 ? $"about {span.Days} months ago" : "about a month ago";
}
return span.Days > 365 ? $"about {span.Days / 365} years ago" : "about a year ago";
}
} }
} }