Solved

# Subtract DateTime and get hours

Posted on 2006-05-08
Medium Priority
1,113 Views
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 ????
0
Question by:Fredy992

LVL 12

Expert Comment

ID: 16630368
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 );

0

LVL 86

Accepted Solution

Mike Tomlinson earned 500 total points
ID: 16630370
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);
MessageBox.Show(ts.TotalHours.ToString());
0

LVL 20

Expert Comment

ID: 16630377
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;

MessageBox.Show(diff.TotalHours.ToString());
0

LVL 20

Expert Comment

ID: 16630380
Very nice: 2 minutes, 3 solutions :-)
0

LVL 96

Expert Comment

ID: 16636041
Yeah, and no response :(

Bob
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
With just a little bit of  SQL and VBA, many doors open to cool things like synchronize a list box to display data relevant to other information on a form.  If you have never written code or looked at an SQL statement before, no problem! ...  give i…
This video tutorial shows you the steps to go through to set up what I believe to be the best email app on the android platform to read Exchange mail.  Get the app on your phone: The first step is to make sure you have the Samsung Email app on your …
###### Suggested Courses
Course of the Month8 days, 4 hours left to enroll