To calculate the difference, simply subtract it as follows:
public TimeSpan TempoPermanencia() {
return HoraSaida - HoraEntrada;
}
This will produce a TimeSpan
that is exactly what you need. DateTime
, contrary to what many people think it is only a point in time, nothing more, so a moment of entry or exit is a point in time. A period, an amount of time spent on something is represented by TimeSpan
. Read his documentation to learn how to use it, take the time stored from the various possible.
Ideally, do not just consider the hour and minute. Can not it be that the exit occurs the next day? Is not there any chance of this happening? Is it such a difference to disregard the seconds? If the seconds are not important, would not it be nice if they were dropped in the data entry? It would even be possible to do this on the property, but would have to use clear criteria. Without certain requirements, no code will be produced right.
I made a more "complete" solution that I do not guarantee that it does exactly what it wants, it lacks criteria to solve certain situations, for example, in the test done can give 1 hour and 43 minutes, or 1 hour and 44 minutes, but it is without clear criterion if this is what it should happen. I did not even try it. Stirring with date and time is much more complicated than it sounds. I cut the superfluous information on the property, but could have stored everything and make that cut account only at the time of calculation.
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 string Placa { get; set; }
public string Modelo { get; set; }
private DateTime horaEntrada;
public DateTime HoraEntrada {
get { return horaEntrada; }
set {
var tempo = default(DateTime).Add(value.TimeOfDay); //corta data
horaEntrada = tempo.AddSeconds(-tempo.Second); //corta segundos
}
}
private DateTime horaSaida;
public DateTime HoraSaida {
get { return horaSaida; }
set {
var tempo = default(DateTime).Add(value.TimeOfDay);
horaSaida = tempo.AddSeconds(-tempo.Second);
}
}
public TimeSpan TempoPermanencia() {
return HoraSaida - HoraEntrada;
}
}
See running on dotNetFiddle and on CodingGround .