How to get time difference between two DateTime variables in C #

1

I have two variables DateTime , which are DataCadastro and DataAtual(DateTime.Now) . I need to know if the time difference between these two dates is greater than or equal to 4 hours. Is there a method in the DateTime class that meets this requirement? Or do I need another alternative?

    
asked by anonymous 23.09.2015 / 15:28

2 answers

5

You need to use TimeSpan for this .

Example:

using System;
using static System.Console;

public class Program
{
    public static void Main()
    {
        var dt1 = DateTime.Now;
        var dt2 = new DateTime(2015, 09, 22, 00, 50, 00);

        TimeSpan ts = dt1 - dt2;

        WriteLine($"Diferença em horas {ts.TotalHours}");
        WriteLine($"Diferença em minutos {ts.TotalMinutes}");
        WriteLine($"Diferença em dias {ts.TotalDays}");            
        WriteLine($"Diferença maior que 4 horas: {ts.TotalHours >= 4}");
    }
}

See working at .Net fiddle

    
23.09.2015 / 15:32
4

It's quite simple:

using System;
using static System.Console;

public class Program {
    public static void Main() {
        var data1 = DateTime.Now;
        var data2 = new DateTime(2015, 9, 23);
        WriteLine($"Diferença: {data1 - data2}");
        WriteLine($"Mais que 4 horas: {data1 - data2 >= new TimeSpan(4, 0, 0)}");
        WriteLine($"Mais que 4 horas (outra forma): {(data1 - data2).TotalHours >= 4}");
        WriteLine($"Mais que 4 horas (se primeira pode ser anterior): {Math.Abs((data2 - data1).TotalHours) >= 4}");
        WriteLine($"Mais que 4 horas (se primeira é anterior): {-(data2 - data1).TotalHours >= 4}");
    }
}

See running on dotNetFiddle .

    
23.09.2015 / 15:34