How to compare date time without time portion in C#

12,603

Solution 1

You just need to compare DateTime.Today and DateTime.Date:

if(_dateJoin.Date > DateTime.Today)
{
    // ...
}
else
{
    // ...
}

Update:

object value has date like Date = {03-16-2016 12:00:00 AM} when execute this line

DateTime _dateJoin =   DateTime.ParseExact(value.ToString(), "MM/dd/yyyy", null);

then i'm getting error like String was not recognized as a valid DateTime. –

That's a different issue, you have to use the correct format provider:

DateTime _dateJoin = DateTime.Parse(value.ToString(), CultureInfo.InvariantCulture);

with ParseExact(not necessary in this case):

DateTime _dateJoin = DateTime.ParseExact(value.ToString(), "MM-dd-yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);

Solution 2

Compare the date parts only:

int cmp = _dateJoin.Date.CompareTo(_CurDate.Date);
Share:
12,603
Thomas
Author by

Thomas

i am developer. i am working with .Net technology (v1.1 & v2.0) last 4 year. i like this forum for fast & good response and that is why i joined this forum. my friends profile id Mou :- http://stackoverflow.com/users/728750/user728750?tab=questions and Keith :- http://stackoverflow.com/users/750398/keith-costa thanks

Updated on July 29, 2022

Comments

  • Thomas
    Thomas almost 2 years

    i tried this way but getting error. here is my code.

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        DateTime _dateJoin = DateTime.ParseExact(value.ToString(), "MM/dd/yyyy", null);
        DateTime _CurDate = DateTime.ParseExact(DateTime.Now.ToString(), "MM/dd/yyyy", null);
    
        int cmp = _dateJoin.CompareTo(_CurDate);
        if (cmp > 0)
        {
            return ValidationResult.Success;
        }
        else if (cmp < 0)
        {
            return new ValidationResult(ErrorMessage);
        }
        else
        {
            return ValidationResult.Success;
        }
    }
    

    the value variable has valid date with time portion too. thanks