开发者

C# On or Before DateTime

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜