C#两个日期的比较用法如下:
DateTime t1;
DateTime t2;
DateTime.Compare(t1,t2)反回整型
值类型 | 条件 |
---|---|
小于零 | t1早于 t2. |
等于零 | t1 等于 t2. |
大于零 | t1 晚于 t2. |
if (DateTime.Compare(this.tbStartDate.Value, this.tbEndDate.Value) > 0)
{
MessageBox.Show("查询起始日期不能大于终止日期,[起始日期]:" + this.tbStartDate.Value.ToString() + " [终止日期]:" + this.tbEndDate.Value.ToString() + "!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Stop);
return;
}
查询时老是提示:查询起始日期不能大于终止日期,如下图:
但从对话框中,看这两个日期是相同的,相同的日期应该返回零值,奇怪!你总不能不让客户查询某一天的数据吧。如果把代码改为如下是可以的:
if (DateTime.Compare(DateTime.Parse(this.tbStartDate.Value.ToString("yyyy-MM-dd")), DateTime.Parse(this.tbEndDate.Value.ToString("yyyy-MM-dd"))) > 0)
{
MessageBox.Show("查询起始日期不能大于终止日期,起始日期:" + this.tbStartDate.Value.ToString() + " 终止日期:" + this.tbEndDate.Value.ToString() + "!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Stop);
return;
}
测试如下,两个DateTimePicker控件的CustomFormat为“yyyy-MM-dd”,日期相同,为2017-5-29
int t1 = DateTime.Compare(this.tbStartDate.Value, this.tbEndDate.Value);
string str1 = this.tbStartDate.Value.ToString("yyyyMMddHHmmss");
string str2=this.tbEndDate.Value.ToString("yyyyMMddHHmmss");
int t2 = DateTime.Compare(DateTime.Parse(this.tbStartDate.Value.ToString("yyyy-MM-dd")), DateTime.Parse(this.tbEndDate.Value.ToString("yyyy-MM-dd")));
t1=1,t2=0,str1 =2017052908155,str2=2017052908155
为什么看上去一样的日期,怎么就出现这种情况呢??