How can I subtract two dates in C#
?
I have two variables DateTime
and I need to get the difference between them in hours.
DateTime fecharegistro = {04/05/2018 8:34:01} //obtenemos este valor de una base de datos
DateTime fechafin = DateTime.Now.Substract(fechaRegistro);
When compiling the above code I get an error saying that an object cannot be implicitly converted TimeStamp
to System.DateTime
, when the variable is DateTime
.
The subtraction of 2 dates will never give you a
DateTime
, but aTimeSpan
. If you want to know the number of hours, simply accessTotalHours
the subtraction property:PS there is no need to use the method
Substract
ofDateTime
. You can just subtract the dates (fecha2-fecha1
).If you want to format the output in a readable way, you can use a format, such as:
This code returns a string of type
04d 01h 44m
The addition or subtraction of dates returns a TimeSpan . Therefore you can get the hours directly from the result of that subtraction.
To find the time difference between two objects of the class
DateTime
you can subtract them both, the result of this operation is an object of the classTimeSpan
, for that reason it does not allow you to assign it to an object of the classDateTime
. For that reason the compiler throws you that error.What is contained in the class object
TimeSpan
is the result of the subtraction of two dates, that is, of the time between both dates:Depending on your needs, you can perform many operations between objects of classes
TimeSpan
andDateTime
. You can also just use the objectTimeSpan
generated from the subtraction of the two dates to print the difference time only.