Calculate Time Duration in Seconds, Minutes, Hours & Weeks

Published on
-
1 min read

For a news site I am currently working on, I needed to display the last time a news article was last published. I wanted to be able to show the duration based on respective major time format. For example, if an article was displayed a couple hours ago, I would want it to to display “2 hours” not “120 minutes”.

More importantly, if an article hadn’t been published to the site more than a week, I don’t want the exact time duration to be displayed. I would prefer the following message: “more than a week ago”. This way, if the site administrator gets really lazy the website viewer will not know the exact time period the site was last updated.

Code:

public class TimePassed
{
    public static string GetPassedTime(DateTime since)
    {
        TimeSpan ts = DateTime.Now.Subtract(since);

        if (ts.Days <= 7)
        {
            switch (ts.Days)
            {
                case 0:
                    switch (ts.Hours)
                    {
                        case 0:
                            switch (ts.Minutes)
                            {
                                case 0:
                                    return String.Format("{0} seconds ago", ts.Seconds);
                                case 1:
                                    return "1 minute ago";
                                default:
                                    return String.Format("{0} minutes ago", ts.Minutes);
                            }
                        case 1:
                            return "1 hour ago";
                        default:
                            return String.Format("{0} hours ago", ts.Hours);
                    }
                case 1:
                    return "yesterday";
                default:
                    return String.Format("{0} days ago", ts.Days);
            }
        }
        else
        {
            return "more than a week ago";
        }
    }
}

Before you go...

If you've found this post helpful, you can buy me a coffee. It's certainly not necessary but much appreciated!

Buy Me A Coffee

Leave A Comment

If you have any questions or suggestions, feel free to leave a comment. I do get inundated with messages regarding my posts via LinkedIn and leaving a comment below is a better place to have an open discussion. Your comment will not only help others, but also myself.