开发者

C# On or Before DateTime

开发者 https://www.devze.com 2023-04-10 10:08 出处:网络
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?

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())
{
}
开发者_JAVA技巧

Would that be right or is there a better way?

Thanks!


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


There are several alternatives how you can do it. For example DateTime.Now - CreatedOn returns a TimeSpan value which says how much time is between these two. You can compare it to 1 hour or less.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号