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";
        }

If you got benefit from this article, feel free to:

ABOUT ME

I’m the Managing Director of an IT Company in Adelaide, South Australia. In my day job I work on both Windows and Linux web hosting technologies and Windows and Web .NET development. In my spare time I create tutorials focused on Davinci Resolve, drone’s, and video production, You can find me on YoutubeTwitter,  or Facebook 

Share

Facebook
Twitter
LinkedIn

Related

Simon Holman Tech
Scroll to Top