Time difference

  • Thread starter Thread starter Vivek Sharma
  • Start date Start date
V

Vivek Sharma

Hi,

I need to calculate the time difference between today 2pm and tomorrow 2 am.
How do I calculate?

Thanks

Vivek
 
You can add and subtract DateTime values and end up with a TimeSpan...
The following code is a very easy representation of how to use it:


DateTime dttoday = DateTime.Now(); // Today's Time
DateTime dttomorrow = DateTime.Now.AddDays(0.5); // 12 hours from now
TimeSpan ts = dttomorrow - dttoday; // Subtract today from "tomorrow"
Debug.WriteLine(ts.TotalHours.ToString()); // Write out hours difference
 
Also, Please disregard the () after .Now - I was writing too fast and
not thinking of what i was doing. It should really look like this:

DateTime dttoday = DateTime.Now;
DateTime dttomorrow = DateTime.Now.AddDays(0.5);
TimeSpan ts = dttomorrow - dttoday;
Debug.WriteLine(ts.TotalHours.ToString());
 
Thanks for your help... What shall I do in case it let us say 2.45pm and
next day 3.25pm. How do I handle this?

Thanks
 
So the answer would be 24.6 hours right? You can aquire this
information by:

DateTime dttoday = DateTime.Parse(@"12/4/2005 2:45 PM");
DateTime dttomorrow = DateTime.Parse(@"12/5/2005 3:25 PM");
TimeSpan ts = dttomorrow - dttoday;
Debug.WriteLine(ts.Days.ToString() + "Days, " + ts.Hours.ToString() +
"Hours, " + ts.Minutes.ToString() + "Minutes");
 
Back
Top