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?


Answer :

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();
        objeto.HoraEntrada = DateTime.Now;
        objeto.HoraSaida = DateTime.Now.AddHours(1).AddMinutes(43).AddSeconds(22);
        WriteLine($"Permaneceu {(objeto.TempoPermanencia().ToString(@"hh:mm"))}");

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

    public DateTime HoraSaida { get; set; }

    public TimeSpan TempoPermanencia() {
        return HoraSaida - HoraEntrada;

See working on .NET Fiddle . And at Coding Ground . Also put it on GitHub for future reference .


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.


    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;
    Console.Write(result.ToString()); // Resultado serĂ¡ 23:00:00

If the variable t2 instantiates by passing the first parameter to zero, you will see that the result will be -01: 00: 00. The above code can be checked here link

So if you persist these fields somewhere, at the moment of persisting you should consider the number of days in your timespan.


Leave a Reply

Your email address will not be published. Required fields are marked *