比较datetimepicker值 [英] compare datetimepicker values

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

问题描述

hii,

如何比较datetimepickers之间的年份,这样必须至少有18年的差距。

我的代码:

  if (dateTimePicker1.Value.Date.CompareTo(dateTimePicker2.Value.Date)<   18 
{
MessageBox.Show( 最低年龄必须为18岁);
}





有什么解决方案吗?

解决方案

这应该足够了:你可以使用运算符''=='',''!='',''< ='',''> ='',''<''和''' >''与 System.DateTime



-SA

首先,Value是DateTime,所以你最后不需要.Date。



其次,CompareTo只是给出一个布尔结果来告诉你一个日期是否早于另一个。



从另一个日期中减去一个日期会导致TimeSpan产生差异天,小时,分钟...显然不是很有帮助,因为很遗憾年数不一样。



所以最简单的解决方案是增加18年到更早的日期。



  //  将18年添加到更早的日期,然后将其与更晚的日期进行比较。 
// 注意我们检查结果是否大于零,因为
// 如果差异小于18年,
// 现在更早的日期将会更晚。
if (dateTimePicker1.Value.AddYears( 18 )。CompareTo( dateTimePicker2.Value)> 0
{
MessageBox.Show(< span class =code-string> 最低年龄必须为18年);
}





免责声明:我没有对此进行测试,因此您可能需要自行解决任何拼写错误!



问候,

Ian。


试试这个



  if ((DateTimePicker1.Value-DateTimePicker2.Value)。年龄 <   18 


hii,
how to compare years between to datetimepickers such that there must be atleast 18 years of gap.
My code:

if (dateTimePicker1.Value.Date.CompareTo(dateTimePicker2.Value.Date) < 18)
           {
               MessageBox.Show("minimum age must be 18 years");
           }



Is there any solution?

解决方案

This should be enough: you can use the operators ''=='', ''!='', ''<='', ''>='', ''<'', and ''>'' with System.DateTime.

—SA


First of all, Value is the DateTime, so you don''t need the ".Date" on the end.

Secondly, CompareTo just gives a boolean result to tell you if one date is earlier than the other.

Subtracting one date from the other results in a TimeSpan, which gives difference in days, hours, minutes... Not very helpful, obviously, because years are unfortunately not all the same length.

So the easiest solution would be to add 18 years to the earlier date.

// Add 18 years to earlier date, and then compare it to the later date.
// Note we check to see if the result is greater than zero because
// if the difference is less than 18 years,
// the earlier date will now in fact be later.
if (dateTimePicker1.Value.AddYears(18).CompareTo(dateTimePicker2.Value) > 0)
{
	MessageBox.Show("minimum age must be 18 years");
}



Disclaimer: I''ve not tested this, so you may have to fix any typos yourself!

Regards,
Ian.


Try this

if((DateTimePicker1.Value-DateTimePicker2.Value).Year < 18)


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

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