slandau
slandau

Reputation: 24102

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 " + 
            "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?

Upvotes: 0

Views: 686

Answers (2)

Fredrik M&#246;rk
Fredrik M&#246;rk

Reputation: 158399

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.");
    }
}

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503869

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.

Upvotes: 9

Related Questions