如何在C#中比较不带时间部分的日期时间 [英] How to compare date time without time portion in C#

查看:442
本文介绍了如何在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 like Date = {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);

这篇关于如何在C#中比较不带时间部分的日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆