开发者

Comparing DateTimes in C#

private void ValidateEffectiveDate()
{
    bool ICAdvanced = SessionManager.DisplayUser.IsInRole(PERMISSIONS.hasICAdvanced);
    if (!ICAdvanced && model.EffectiveDate < DateTime.Now)
    {
         this.CheckAndAddValidation("EffectiveDate",
            "You do not have the advanced permission, so you " + 
 开发者_StackOverflow中文版           "are unable to value historical indications.");
    }
}

If you are NOT ICAdvanced, you should NOT be able to have a date that is in the past, one day before today or earlier. However, you CAN have today or in the future.

Why is this code not reflecting that correctly?


Well, you're going from now, rather than today for one thing. If "now" is 5pm, but EffectiveDate is midnight today, then currently that's going to add a validation error.

So you might want:

if (!ICAdvanced && model.EffectiveDate < DateTime.Today)

However, you also need to work out how model.EffectiveDate is represented. DateTime is very unfortunate of its handling of time zones, as a value can be UTC, local or unspecified. I'm not currently clear on how that affects comparisons (if I compare "local midnight" with a "UTC midnight" in a time zone of UTC+5, what should the result be)? I think it treats both of them as being local, so it would compare "local midnight" and "UTC midnight" as being the same. Worth thinking about though.


I would say that the problem is that you are forcing it to be after the current instant, not today or later. It should perhaps be like this instead:

private void ValidateEffectiveDate()
{
    bool ICAdvanced = SessionManager.DisplayUser.IsInRole(PERMISSIONS.hasICAdvanced);
    if (!ICAdvanced && model.EffectiveDate < DateTime.Now.Date)
    {
        this.CheckAndAddValidation("EffectiveDate", "You do not have the advanced permission, so you are unable to value historical indications.");
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜