Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: calculating time diff

Tags:

c#

using the following:-

TimeSpan diff = dt2.TimeOfDay - dt1.TimeOfDay;

d1, d2 are 2 variables of type DateTime and they have got values in them

Now I want to check if there's a difference of 12 hours b/w them

if(diff>12)

{
//do stuff
}

now of course it wont wont coz 12 is an int..so how do I check if the time is more than 12 hrs or not ?? need help with this if statement only..thnx

like image 858
Serenity Avatar asked Nov 27 '25 15:11

Serenity


1 Answers

The general solution is to construct a TimeSpan object that corresponds to the cut-off:

if(diff > TimeSpan.FromHours(12))
{
   ...
}

If the cut-off corresponds to a multiple of a 'nice' unit of time like days, hours, minutes, seconds or milliseconds as in your example, you could use the TotalXXX property of TimeSpan, as others have posted:

if(diff.TotalHours > 12)
{
   ...
}
like image 157
Ani Avatar answered Nov 29 '25 03:11

Ani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!