C#: Get elapsed time as text from post date
This little snippet returns the elapsed time in a textual form from a specific date. Either as "x days ago", "x hours ago" or "x minutes ago" (using singularis for "1 minute ago" etc). Suitable for timelines.
public static string GetSpan(DateTime date) {
TimeSpan time = DateTime.Now - date;
if (time.Days > 0) {
return time.Days + (time.Days > 1 ? " days " : " day ") + "ago";
}
else if (time.Hours > 0) {
return time.Hours + (time.Hours > 1 ? " hours " : " hour ") + "ago";
}
return time.Minutes + (time.Minutes > 1 ? " minutes " : " minute ") + "ago"; ;
}
Related posts: