How to subtract hours from a DateTime?

1

I have a DateTime and I need to subtract hours from one column to the other. For example, I want to subtract 12:45:00 - 12:25:00 and have the result 20 .

This is the code I'm using

        for (int i=0; i<n; i++)
        {
            DateTime fecha1 = Convert.ToDateTime(inicio[i].ToString("HH:mm:ss"));
            DateTime fecha2 = Convert.ToDateTime(arrayhrllegada[i].ToString("HH:mm:ss"));
            //var duration = Math.Round(fecha1 - fecha2, 1);
            double horas = Math.Round(fecha2.Subtract(fecha1).TotalMinutes,1);

            dataGridView1.Rows[i].Cells[7].Value = horas.ToString();
        }

It's Start minus Arrival and the result is Wait Time

    
asked by tecch5510 13.12.2018 в 04:13
source

2 answers

4

To subtract dates you can use Subtract() of DateTime

DateTime.Subtract Method

a serious example

DateTime fecha1 = Convert.ToDatetime("12:45:00");
DateTime fecha2 = Convert.ToDatetime("12:25:00");

double horas = fecha2.Subtract(fecha1).TotalHours;

TimeSpan.TotalHours Property

    
answered by 13.12.2018 в 05:32
0

You can use the TimeSpan for the difference of hours in the following way:

TimeSpan diferenciaHoras = new TimeSpan();
DateTime fechaInicio = new DateTime();
fechaInicio = DateTime.Parse("12:25:00");

DateTime fechaLlegada = new DateTime();
fechaLlegada = DateTime.Parse("13:30:00");

diferenciaHoras = fechaLlegada - fechaInicio;
int horas = diferenciaHoras.Hours;
double horasTotales = diferenciaHoras.TotalHours;

In this example, between 12:25 and 13:30 there is an hour with 5 minutes. The TotalHours property will give you the result of 1,083 which is the hour plus 0.083 hours equivalent to 5 minutes.

If you need it in minutes, then you use the TotalMinutes property or multiply the hours obtained by 60.

double minutos = diferenciaHoras.TotalMinutes;

O

double minutos = horasTotales * 60;
    
answered by 17.12.2018 в 19:11