# TimeSpan time difference in 24hr format

Posted on

#### Question :

I am asking this question because I have not located any topic with my problem, which is very similar to others.

I have 2 fields `TimeSpan?` with one referring to the entry time and the other to the exit time .

I want to know the time difference, so if the person works from 8:00 a.m. to 10:00 p.m., he worked 2 hours.

This is quite simple, maybe with a Compare or a sub I can extract this total value, however when I inform that the person entered at 5:00 p.m. and left at 4:00 p.m. he returns me 1, being that he worked 23 hours

How can I do this calculation?

There’s a mess there.

You need to answer a period , a time interval, so the response will be `TimeSpan` .

The data entry is the time of entry and time of exit, so they are two points in time , ie they must be `DateTime` .

When it starts wrong it gets hard to do right. Turn those hours into `DateTime` and then just subtract.

``````using System;
using static System.Console;

public class Program {
public static void Main() {
var objeto = new AlgumaClasse();
WriteLine(\$"Permaneceu {(objeto.TempoPermanencia().ToString(@"hh:mm"))}");
}
}

class AlgumaClasse {
public DateTime HoraEntrada { get; set; }

public DateTime HoraSaida { get; set; }

public TimeSpan TempoPermanencia() {
}
}
``````

TimeSpan has the option of having days as well. In the constructor it has an overload that you inform (days, hours, minutes, seconds) and if you inform the amount of days the calculation will be more precise.

Example:

``````    TimeSpan t1 = new TimeSpan(0,17,0,0);
TimeSpan t2 = new TimeSpan(1,16,0,0); //Repare que aqui tem um dia.

var result = t2-t1;