比较C#中的日期 [英] comparing dates in C#

查看:133
本文介绍了比较C#中的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该如何比较C#中的日期.范例d1 = 2012年2月1日,d2 = 2012年1月1日

如果没有错误提示,则条件d2必须大于d1

我该怎么办?

在此先感谢

how do i compare dates in C#. example d1 = february 1, 2012, d2 = january 1, 2012

condition d2 must be greater than d1 if not an error prompt occur

how do i do this?

thanks in advance

推荐答案

这只是一个简单的示例,我建议您使用TryParse而不是parse,但是该示例足以说明要做什么:

This is only a simple example and I advise you to use TryParse instead of parse, but the example is sufficient to illustrate what to do:

static void Main()
{
    DateTime d1 = DateTime.Parse("February 1, 2012"); // Better to use TryParse here
    DateTime d2 = DateTime.Parse("January  1, 2012"); // ditto

    if (DateTime.Compare(d1, d2) < 0) // also possible to use d1.CompareTo(d2). If the result is less than zero d1 is less than d2
    //if (d1 < d2) // As Youssef pointed out the normal relational less than or greater than operator can also be used
    {
        Console.WriteLine("Everything OK!");
    }
    else
    {
        Console.WriteLine("Do what ever you see fit in the error case!");
    }
}


这很简单,很正常,我的朋友:
It is easy and normal, my friend:
if(d1 < d2)
{
    // Code in case of correct date relation
}
else
{
    // Code in case of error (d2 less than or equal to d1)
}


使用TimeSpan Compare ^ ].


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

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