Reputation: 52037
I want to calculate the difference between two DateTimes. This is what I have:
if ((DateTime.Now.Date - TheUTCDateTime.Date).TotalMinutes > 180)
{
ValidObject = false;
}
Basically, I want to make sure that TheUTCDateTime
is not more than 3 hours old. Is what I am doing the best way to do this?
Upvotes: 0
Views: 76
Reputation: 2289
If you want to check whether TheUTCDateTime
is older than 3 hours, you shouldn't be using the .Date
property:
DateTime.UtcNow - TheUTCDateTime > TimeSpan.FromHours(3)
Upvotes: 1
Reputation: 144206
You probably don't want to extract the date and maybe want to use UtcNow
instead of Now
.
You can also use TimeSpan.FromHours
for the period:
if ((DateTime.UtcNow - TheUTCDateTime) > TimeSpan.FromHours(3))
or simply
ValidObject = (DateTime.UtcNow - TheUTCDateTime) <= TimeSpan.FromHours(3);
Upvotes: 3
Reputation: 460268
Your approach is ok, but you could improve it a little bit:
TimeSpan span = DateTime.Now - TheUTCDateTime.Date;
ValidObject = span.TotalHours <= 3;
Since you want to check the hours i have used TotalHours
, i have used DateTime.Now
instead of Date
which truncates the time and i set it also to true
whereas your code only sets it to false
.
Upvotes: 1