C# Get Date Difference

by aherrick 5. September 2008 04:21

I was working on my Twitter extension to display my most recent tweet and I wanted to display how long ago I tweeted.  I was able to acquire some code which I tweaked a bit to fit my needs.  Check it out!

This method accepts two dates that you want to compare.  For example: In my case, date1 is "DateTime.Now" and date2 is the Tweet date (whenever my most recent tweet was).  I will have a full post on the twitter extension you see above soon!

Take a look at the code below!

    private string GetDifferenceDate(DateTime date1, DateTime date2)
    {
        if (DateTime.Compare(date1, date2) >= 0)
        {
            TimeSpan ts = date1.Subtract(date2);
            // if more than 1 day ago
            if (ts.Days > 0)
                return string.Format("{0} days, {1} hours, {2} minutes", 
                ts.Days, ts.Hours, ts.Minutes);
            else
                return string.Format("{0} hours, {1} minutes", ts.Hours, ts.Minutes);

        }
        else
            return "Not valid";
    }

Tags:

Comments

8/6/2009 4:59:53 AM #

Josh (membership blueprints coding)

Nice date-difference method.

I love your enthusiasm for coding, like everything's a real adventure. You're a good role model for other programmers. And congratulations on getting a great job!

BTW I used to use String.Format but found it really cumbersome so added an extension method which I found on StackOverflow, usage like:

"{0} days, {1} hours, {2} minutes".Put(ts.Days, ts.Hours, ts.Minutes);

It's much more natural IMHO, though being a hobbyist programmer there's a bit more flexibility than in the workplace. Anyway, just a thought.

Here's the code:
[code]
/// <summary>
/// Enables a more natural "Result: {0}".Put(result)
/// </summary>
public static string Put(this string s, params object[] args)
{
   return string.Format(s, args);
}
[/code]

Josh (membership blueprints coding) United States



Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen
Tweaked by ajondeck.NET

About the author

Andrew Herrick
I am a full time developer for Blue Horseshoe Solutions based out of Carmel, Indiana. I enjoy learning new technology and hope to give back with some of the cool things I pick up along the way.  Check me out on Stack Overflow!


Categories

None

Recent comments

Comment RSS

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in  anyway.

© Copyright 2008