241

I am retrieving two date time values from the database. Once the value is retrieved, I need the difference between the two values. For that, I create a timespan variable to store the difference of the 2 date values.

TimeSpan? variable = datevalue1 - datevalue2;

Now i need to show the difference which is stored in the Timespan variable in terms of number of hours. I referred to TimeSpan.TotalHours but couldn't apply the same for some reason. How do I do that? I am using C# on a MVC project. I simple need to show the difference value in hours?

EDIT: Since timespan was nullable, i couldn't use the total hours property. Now I can use it by doing TimeSpanVal.Value.TotalHours;

5
  • 3
    Why could you not use TimeSpan.TotalHours? Commented Feb 9, 2011 at 14:40
  • it doesnt allow me to. i tried. :(
    – reggie
    Commented Feb 9, 2011 at 14:45
  • is it because my timespan is nullable that i cannot use the totalhours property?
    – reggie
    Commented Feb 9, 2011 at 14:46
  • 4
    See example of datetime difference, Hours Difference, Minutes difference on codegateway.com/2012/01/c-datetime-difference.html
    – user1240789
    Commented Feb 29, 2012 at 17:35
  • 1
    the TimeSpan object has total hours in .Value.TotalHours
    – smurtagh
    Commented Apr 26, 2018 at 12:38

8 Answers 8

276

you may also want to look at

var hours = (datevalue1 - datevalue2).TotalHours;
2
  • but in this case system shows " 'System.Nullable<System.TimeSpan>' does not contain a definition for 'TotalHours' and no extension method 'TotalHours' accepting a first argument of type 'System.Nullable<System.TimeSpan>' could be found ". Can you please tell me the reason for it?
    – Neha
    Commented May 6, 2015 at 11:06
  • 9
    Nullable would need a .Value.TotalHours instead of just .TotalHours. It's a factor of the nullable wrapping. You could alternatively cast it as a timespan --> ((TimeSpan) (nullabledatevalue1 - nullabledatevalue2)).TotalHours Commented May 6, 2015 at 15:58
136

I think you're confused because you haven't declared a TimeSpan you've declared a TimeSpan? which is a nullable TimeSpan. Either remove the question mark if you don't need it to be nullable or use variable.Value.TotalHours.

0
125

In the sample, we are creating two datetime objects, one with current time and another one with 75 seconds added to the current time. Then we will call the method .Subtract() on the second DateTime object. This will return a TimeSpan object. Once we get the TimeSpan object, we can use the properties of TimeSpan to get the actual Hours, Minutes and Seconds.

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 );

Result:

Time Difference (seconds): 15
Time Difference (minutes): 1
Time Difference (hours): 0
Time Difference (days): 0
1
  • 36
    You want to use "Total" such as TotalSeconds, TotalMinutes etc Commented Feb 9, 2011 at 14:44
41

Is there a reason you're using Nullable?

If you want to use Nullable then you can write variable.Value.TotalHours.

Or you can just write: (datevalue1 - datevalue2).TotalHours.

4
  • Probably because datevalue1 or datevalue2 are DateTime? Commented Feb 9, 2011 at 14:44
  • @Filip, it's ok, they should be DateTime. In .NET, DateTime - DateTime = TimeSpan. Commented Feb 9, 2011 at 14:46
  • 2
    @Illya, I mean that They are probably Nullable<DateTime> and therefore you get a Nullable<TimeSpan>. Commented Feb 9, 2011 at 14:47
  • Your answer is really effective. I was looking for it.
    – Ananda G
    Commented Jul 31, 2017 at 5:35
8

Here is another example of subtracting two dates in C# ...

if ( DateTime.Now.Subtract(Convert.ToDateTime(objDateValueFromDatabase.CreatedOn)).TotalHours > 24 ) 
{ 
... 
} 
4

a more precise way for employee paid hours or other precision requirement::

decimal DeterminePreciseHours(DateTime startTimestamp, DateTime stopTimestamp)
{
    var span = (stopTimestamp - startTimestamp).Value;
    decimal total = (decimal)span.TotalMilliseconds / 60 / 60 / 1000;
    return Math.Round(total, PRECISION_CONSTANT);
}

https://dotnetfiddle.net/tVIoVJ

2
var startTime = new TimeSpan(6, 0, 0); // 6:00 AM
var endTime = new TimeSpan(5, 30, 0); // 5:30 AM 
var hours24 = new TimeSpan(24, 0, 0);
var difference = endTime.Subtract(startTime); // (-00:30:00)
difference = (difference.Duration() != difference) ? hours24.Subtract(difference.Duration()) : difference; // (23:30:00)

can also add difference between the dates if we compare two different dates

new TimeSpan(24 * days, 0, 0)
0

WOW, I gotta say: keep it simple:

MessageBox.Show("Result: " + (DateTime.Now.AddDays(10) > DateTime.Now));

Result: True

and:

MessageBox.Show("Result: " + DateTime.Now.AddDays(10).Subtract(DateTime.Now));

Result: 10.00:00:00

The DateTime object has all the builtin logic to handle the Boolean result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.