Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare date time without time portion in C# [duplicate]

Tags:

c#

datetime

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

like image 574
Thomas Avatar asked Sep 02 '25 14:09

Thomas


1 Answers

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);
like image 85
Tim Schmelter Avatar answered Sep 05 '25 16:09

Tim Schmelter