如何在C#中比较不带时间部分的日期时间
问题描述:
我尝试过这种方式,但是出错了。这是我的代码。
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
答
您只需要比较 DateTime.Today
和 DateTime.Date
:
You just need to compare DateTime.Today
and DateTime.Date
:
if(_dateJoin.Date > DateTime.Today)
{
// ...
}
else
{
// ...
}
更新:
object
值的日期类似于Date = {03-16-2016 12:00:00 AM}
,当
执行此行时
object
value has date likeDate = {03-16-2016 12:00:00 AM}
when execute this line
DateTime _dateJoin = DateTime.ParseExact(value.ToString(), "MM/dd/yyyy", null);
然后我遇到类似String的错误,无法识别为有效字符串约会时间。 –
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);
带有 ParseExact
(在这种情况下不是必需的) ):
with ParseExact
(not necessary in this case):
DateTime _dateJoin = DateTime.ParseExact(value.ToString(), "MM-dd-yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);