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

Asked

Viewed 10,665 times

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 any method in the class DateTime that meets my requirement? Or I need another alternative?

2 answers

6


You need to use TimeSpan for that reason.

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 on .Net fiddle

5

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}");
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.