C#:如何比较两个日期

时间:2012-04-23 15:40:30

标签: c# datetime

我想将DD/MM/YYYY表格中存储的日期与当前日期进行比较。

我需要知道它是否早于或晚于DateTime.Now ...

有人有想法建议吗?

提前谢谢。

3 个答案:

答案 0 :(得分:5)

您可以使用DateTime.Compare

var result = DateTime.Compare(Convert.ToDateTime(TextBox1.Text), DateTime.Today);
string relationship;

if (result < 0)
   relationship = "is earlier than";
else if (result == 0)
   relationship = "is the same time as";         
else
   relationship = "is later than";

Console.WriteLine("{0} {1} {2}", date1, relationship, date2);

有关详细信息,请参阅MSDN上的documentation

答案 1 :(得分:1)

您可以使用以下代码将时间戳解析为DateTime对象,然后根据需要进行比较。

DateTime date;
DateTime.TryParseExact("12/03/2009", "dd/MM/yyyy", null, DateTimeStyles.None, out date);

在此处查看更多http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

答案 2 :(得分:0)

这可以使用DateTime.Compare方法完成:

date1 = Convert.ToDateTime(TextBox1.Text)
date2 = DateTime.Today
var result = DateTime.Compare(date1, date2)
string relationship

if (result < 0)
   relationship = "is earlier than";
else if (result == 0)
   relationship = "is the same time as";         
else
   relationship = "is later than";

Console.WriteLine("{0} {1} {2}", date1, relationship, date2);