Skip to main content

Humanize elapsed time from some Time instance to DateTime.Now, e.g. '1 minute ago'.

public static string TimeAgo(DateTime date)
{
    var now = DateTime.UtcNow;
    var min = (now - date).TotalMinutes;

    if (min < 1)
        return "just now";
    if (min < 60)
        return string.Format("{0} min ago", (int)min);
    if (min < 1440)
        return string.Format("{0} hours ago", (int)(min / 60));
    if (min < 43200)
        return string.Format("{0} days ago", (int)(min / 1440));
    if (min < 518400)
        return string.Format("{0} months ago", (int)(min / 43200));

    return string.Format("{0} years ago", (int)(min / 518400));
}