c# – TimeSpan time difference in 24hrs format

Question:

I'm asking this question because I couldn't find any topic with my problem, which is very similar to others.

Do I have 2 TimeSpan? fields TimeSpan? where one refers 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 am to 10:00 am, he worked 2 hours.

This is very simple, maybe with a Compare or a sub I can extract this total value, but when I inform that the person came in at 17:00 and left at 16:00 he returns 1, since he worked 23 hours

How can I make this calculation?

Answer:

There is confusion there.

You need to answer a period , a time span, so the answer will be a TimeSpan .

Input is the input time and output time, so they are two points in time , that is, they must be DateTime .

When it starts wrong, it's hard to do it right. Transform these hours into DateTime and then just do a subtraction.

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() => HoraSaida - HoraEntrada;
}

See working on ideone . And in .NET Fiddle . Also posted on GitHub for future reference .

Scroll to Top