如何在C#.net中比较日期 [英] how can i compare the dates in C#.net
本文介绍了如何在C#.net中比较日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,
如果我有两个文本框并给出两个日期.
我正在检查第二个文本框日期应大于第一个文本框日期.
如何在C#.net中比较日期?
例如
TextBox1.Text =''2011-06-16T05:07:57 + 0000''
TextBox2.Text =''2011-06-16T06:07:57 + 0000''
请帮助我.
Hi All,
If I have two textboxes and I give two dates.
I am checking the second textbox date should be greater than the first textbox date.
How can I compare the dates in C#.net?
for e.g.
TextBox1.Text=''2011-06-16T05:07:57+0000''
TextBox2.Text=''2011-06-16T06:07:57+0000''
Please help me.
推荐答案
不要将字符串与日期的字符串表示形式进行比较,以结构System.DateTime
的形式比较时间值.
首先,您真的必须在编辑框中输入此数据吗?一些日期时间或日历选择器可行吗? —它会首先为您提供结构的价值.
例如,看这篇文章:
DateTimePicker Web控件 [System.TimeSpan的形式返回结果.这是一组全面的运算符,可以满足您的所有比较需求.
—SA
Don''t compare strings with string representation of dates, compare time values in the form of structureSystem.DateTime
.
First of all, do you really have to enter this data in edit box? Is some date-time or calendar picker feasible? — it would provide you with the value of the structure in first place.
For example, look at this article:
DateTimePicker Web Control[^].
If you still want to get time from text, the conversion shown by Debata is correct.
When you have two instances ofDateTime
structure you can use operators "==", "!=" and ">", "<", ">=", "<=" in the sense "later", "earlier", "not earlier", "not later", respectively. Also, you can use subtraction operator ("-") which returns the result in the form ofSystem.TimeSpan
. This is a comprehensive set of operators to cover all your comparison needs.
—SA
您应该使用日期时间选择器"控件而不是文本框,这对于开发人员来说更专业.
You should use "date time picker" control instead of text boxes this is more professional as a developer.
DateTime fromdate = Convert.ToDateTime(TextBox1.Text);
DateTime todate = Convert.ToDateTime(TextBox2.Text);
if (todate.CompareTo(fromdate) < 0)
{
//add you logic
}
这篇关于如何在C#.net中比较日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文