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:
Console.WriteLine(tiempoDiferencia.TotalHours);
Among many other things.