Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# On or Before DateTime

Tags:

c#

asp.net

I want to write if If statement that executes if the CreatedDate is on or before the next 1 hour. Is there a way to do this?

Something like:

if (CreatedOn.ToUniversalTime() <= DateTime.Now.AddHours(1).ToUniversalTime())
{
}

Would that be right or is there a better way?

Thanks!


1 Answers

I think your approach is mostly fine. After all, look at your description:

"if the CreatedDate is on or before the next 1 hour"

That doesn't talk about subtracting one time from another - it talks about comparing CreatedDate with "the next hour" i.e. one hour from now.

So:

DateTime hourFromNowUtc = DateTime.UtcNow.AddHours(1);
if (CreatedOn.UniversalTime() <= hourFromNowUtc)

that looks pretty clean to me - except you need to be aware of what CreatedOn really is. Is it local? Unspecified? Already universal? Unfortunately DateTime is problematic in this respect... if you were using Noda Time there'd be no cause for doubt ;)

like image 160
Jon Skeet Avatar answered Feb 27 '26 12:02

Jon Skeet