Subtract two dates in c #


How can I subtract two dates in C #?

I have two DateTime variables and I wanted to return the result in hours of them.

DateTime fecharegistro = {04/05/2018 8:34:01} //obtenemos este valor de una bbdd
DateTime fechafin = DateTime.Now.Substract(fechaRegistro);

I have looked at examples but I can not get this to compile. It tells me that you can not implicitly convert a TimeStamp obj in System.dateTime, when the variable is DateTime.

asked by Aritzbn 07.05.2018 в 16:06

3 answers


Subtracting 2 dates will never give you a DateTime , but a TimeSpan . If you want to know the number of hours, simply access the property TotalHours of subtraction:

DateTime fecharegistro = DateTime.Parse("04/05/2018 8:34:01"); //obtenemos este valor de una bbdd
var horas = (DateTime.Now-fecharegistro).TotalHours;

P.D. it is not necessary to use the Substract of DateTime method. You can simply subtract the dates ( fecha2-fecha1 ).

If you want to format the result in a legible way, you can use a format, such as:

var horas = (DateTime.Now - fecharegistro).ToString(@"dd\d\ hh\h\ mm\m\ ");

This code returns a string of type 04d 01h 44m

answered by 07.05.2018 / 16:13

Adding or subtracting dates returns you a TimeSpan . Therefore, you can obtain the hours directly from the result of that subtraction.

var fecharegistro = DateTime.Parse("04/05/2018 8:34:01");
var timeSpan = DateTime.Now - fecharegistro;

answered by 07.05.2018 в 16:13

To find the time difference between two objects of the class DateTime you can subtract them both, the result thrown from this operation is an object of the class TimeSpan , for that reason it does not allow you to assign it to an object of the class DateTime . 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, the time between both dates:

TimeSpan tiempoDiferencia = DateTime.Now - fecharegistro;

Depending on your needs, you can perform many operations between objects of the classes TimeSpan and DateTime . You can also only use the TimeSpan generated from the subtraction of the two dates to print the difference time only.


For example:


Add the time difference to today's date:

DateTime resultado = DateTime.Today + tiempoDiferencia;

Add the difference time to the current time:

DateTime resultado = DateTime.Now + tiempoDiferencia;

Store the difference time between both dates as text:

string tiempo = tiempoDiferencia.ToString();

Print the time difference between both dates:


Among many other things.

answered by 07.05.2018 в 16:17