Subtract DateTime and get hours

Posted on 2006-05-08
Last Modified: 2012-06-27
I have 2 dates. First date is '12/27/2002' and the other '12/24/2002'. I need to subtract these two dates and show the diference bettween them in hours ??? How can I do this ????
Question by:Fredy992
    LVL 12

    Expert Comment

    Here's an example:

    DateTime startTime = DateTime.Now;

    DateTime endTime = DateTime.Now.AddSeconds( 75 );
     TimeSpan span = endTime.Subtract ( startTime );
     Console.WriteLine( "Time Difference (seconds): " + span.Seconds );
     Console.WriteLine( "Time Difference (minutes): " + span.Minutes );
     Console.WriteLine( "Time Difference (hours): " + span.Hours );
     Console.WriteLine( "Time Difference (days): " + span.Days );

    LVL 85

    Accepted Solution

    Like so....

                String strDtA = "12/27/2002";
                String strDtB = "12/24/2002";
                DateTime dtA = DateTime.Parse(strDtA);
                DateTime dtB = DateTime.Parse(strDtB);
                TimeSpan ts = dtA.Subtract(dtB);
    LVL 20

    Expert Comment

    DateTime dt1 = DateTime.ParseExact("12/27/2002", "MM/dd/yyyy", null);
    DateTime dt2 = DateTime.ParseExact("12/24/2002", "MM/dd/yyyy", null);

    TimeSpan diff = dt1 - dt2;

    LVL 20

    Expert Comment

    Very nice: 2 minutes, 3 solutions :-)
    LVL 96

    Expert Comment

    by:Bob Learned
    Yeah, and no response :(


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Looking for New Ways to Advertise?

    Engage with tech pros in our community with native advertising, as a Vendor Expert, and more.

    This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
    Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
    To add imagery to an HTML email signature, you have two options available to you. You can either add a logo/image by embedding it directly into the signature or hosting it externally and linking to it. The vast majority of email clients display l…
    Sending a Secure fax is easy with eFax Corporate ( First, Just open a new email message.  In the To field, type your recipient's fax number You can even send a secure international fax — just include t…

    779 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    14 Experts available now in Live!

    Get 1:1 Help Now