954,514 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Calculate "time ago" - time that passed since a DateTime

I've been searching like crazy for this but can't find anything in C#/VB.NET.

I want to show off a DateTime as a "x days x hours x minutes x seconds ago" string, so I'm looking for a function that calculates the time difference between a DateTime and the current date and time, and shows it in that nice string that you can see everywhere around the web these days.

Preferably something like what geekpedia.com has on its frontpage. Note that it always shows the two most relevant time objects at once. For example for the newer posting it shows "17 hours, 31 minutes ago" and for the older ones it shows "3 days, 19 hours ago" -- it doesn't keep showing minutes, seconds, unless relevant.

If anyone happens to have a C#/VB.NET function for this, it will be much appreciated.

Thanks!

art vandelay
Newbie Poster
5 posts since Nov 2007
Reputation Points: 10
Solved Threads: 0
 

Here you are

static void Main(string[] args)
        {
            Console.WriteLine(GetDifferenceDate(new DateTime(2008, 11, 25, 10, 30, 2), 
                new DateTime(2008, 6, 2, 6, 3, 5)));
        }

        static string GetDifferenceDate(DateTime date1, DateTime date2)
        {
            if (DateTime.Compare(date1, date2) >= 0)
            {
                TimeSpan ts = date1.Subtract(date2);
                return string.Format("{0} days, {1} hours, {2} minutes, {3} seconds", 
                    ts.Days, ts.Hours, ts.Minutes, ts.Seconds);
            }
            else
                return "Not valid";
        }
Ramy Mahrous
Postaholic
2,196 posts since Aug 2006
Reputation Points: 480
Solved Threads: 276
 

Thanks a lot!

This code is so much simpler than similar functions I've seen for other languages (such as PHP.) Guess we owe it to the versatility of the DateTime class.

art vandelay
Newbie Poster
5 posts since Nov 2007
Reputation Points: 10
Solved Threads: 0
 

You're welcome, hope it helped!
Please mark your thread solved if it been.

Ramy Mahrous
Postaholic
2,196 posts since Aug 2006
Reputation Points: 480
Solved Threads: 276
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You