A function to convert a TimeSpan to an x minutes ago string

An application I’m working on requires a facebook style status system and I thought it would be good to include the “posted x minutes ago” text after the status.

I’m sure my code is not the most elegant solution but it works so I thought I’d share.

public static String LastUpdatedText(DateTime DateNow, DateTime LastUpdated)
        {
            TimeSpan timeDiff = DateNow.Subtract(LastUpdated);

            if (timeDiff.TotalHours < 1)
            {
                return Math.Round(timeDiff.TotalMinutes,0) + " minutes ago";
            }

            if (timeDiff.TotalHours < 24)
            {
                return Math.Round(timeDiff.TotalHours, 0) + " hours ago";
            }

            if (timeDiff.TotalHours < 48)
            {
                return "yesterday";
            }

            if (timeDiff.TotalHours < 168)
            {
                return Math.Round(timeDiff.TotalDays,0) + " days ago";
            }

            if (timeDiff.TotalDays < 42)
            {
                return Math.Round((timeDiff.TotalDays / 7),0) + " weeks ago";
            }

            if (timeDiff.TotalDays < 365)
            {
                return Math.Round((timeDiff.TotalDays / 30),0) + " months ago";
            }

            return Math.Round((timeDiff.TotalDays / 365),0) + " years ago";
        }

2 thoughts on “A function to convert a TimeSpan to an x minutes ago string

  1. Useful function Simon. Have you thought about maybe converting it to an extension method of DateTime. Perhaps GetDifference(DateTime date)?

Leave a Reply