How To Calculate "Time Ago" In C#

Written some days ago
How To Calculate "Time Ago" In C#

You see this time format all over the internet nowadays. Posted 3 hours ago. You can see in any of a number of situations. For example, how along ago comments were posted or how long ago a blog post was published.

Here is a quick implementation in C# that gets the job done. This is a very generic function, so you can place it wherever you keep your most used functions and just call it whenever it is needed. It relies on the TimeSpan objects broken down properties, such as days, hours, minutes and seconds. It uses the DateTime classes Subtract method, which subtracts the passed in date with the objects current date.

The resulting TimeSpan object contains all of the time intervals that we're going to be needing to display our date properly. After that we just run through each of these values displays the largest units first, such as Days.


    // return how much time passed since date object
    public static string GetTimeSince(DateTime objDateTime)
    {
        // here we are going to subtract the passed in DateTime from the current time converted to UTC
        TimeSpan ts = DateTime.Now.ToUniversalTime().Subtract(objDateTime);
        int intDays = ts.Days;
        int intHours = ts.Hours;
        int intMinutes = ts.Minutes;
        int intSeconds = ts.Seconds;

        if (intDays > 0)
            return string.Format("{0} days", intDays);

        if (intHours > 0)
            return string.Format("{0} hours", intHours);

        if (intMinutes > 0)
            return string.Format("{0} minutes", intMinutes);

        if (intSeconds > 0)
            return string.Format("{0} seconds", intSeconds);

        // let's handle future times..just in case
        if (intDays < 0)
            return string.Format("in {0} days", Math.Abs(intDays));

        if (intHours < 0)
            return string.Format("in {0} hours", Math.Abs(intHours));

        if (intMinutes < 0)
            return string.Format("in {0} minutes", Math.Abs(intMinutes));

        if (intSeconds < 0)
            return string.Format("in {0} seconds", Math.Abs(intSeconds));

        return "a bit";
    }


The function assumes a DateTime object with a UTC time passed in. If your time is not in UTC, you don't need to convert the DateTime.Now to UTC.



TimeSpan ts = DateTime.Now.Subtract(objDateTime);

The TimeSpan object represents an interval that is measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. The Subtract function of the DateTime class will return a TimeSpan with the interval between both days. The highest measurement of time that the TimeSpan uses is Days, for consistency. So we start there and work our way down to seconds.

Just copy and paste that into your helper functions library and you're good to go. But feel free to clean it up and improve it in any way. Maybe passing in a boolean value indicating whether to handle UTC would be a nice touch.

Walter G. author of blog post
Walter Guevara is a Computer Scientist, software engineer, startup founder and previous mentor for a coding bootcamp. He has been creating software for the past 20 years.
#C#

Get the latest programming news directly in your inbox!

Have a question on this article?

You can leave me a question on this particular article (or any other really).

Ask a question

Community Comments

No comments posted yet

Add a comment