检查日期是否为真 [英] Checking to see if date is true
本文介绍了检查日期是否为真的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,检查日期是否是正确的日期时出现了一个小问题,即时检查日期是否不超过31天,并检查"To date"是否大于从日期"这两个功能正常工作,但现在我要检查这些日期是否有效,因此您不能说"2012/10/45",
我该怎么做,我的日期代码如下所示
Hi all, got a slight problem when checking to see if the date is a proper date, im checking to see if the date is no more than 31 days and also to check if the "To date" is greater than the "From Date" those 2 functions work but now i got to check if those dates are valid so you cant for example say "2012/10/45",
how can i do this my code for the date is as follows
{
DateTime dt = Convert.ToDateTime(TextBox1.Text);
DateTime dta = Convert.ToDateTime(TextBox2.Text);
TimeSpan pp = dta - dt;
int days = pp.Days;
string s = TextBox1.Text;
string t = TextBox2.Text;
DateTime theDateA = DateTime.Parse(s);
DateTime theDateB = DateTime.Parse(t);
if (theDateB > theDateA)
{
if (days > 31)
{
TextBox1.BackColor = System.Drawing.Color.Red;
TextBox2.BackColor = System.Drawing.Color.Red;
date_Error_cell.Text = "Select a DATE NOT more than 31 days";
date_Error_cell.Attributes.Add("style", "font-weight:bold; text-align:center; font-family:Calibri; color:Red; font-size:large;");
Monthly_Spend();
label();
}
else
{
TextBox1.BackColor = System.Drawing.Color.White;
TextBox2.BackColor = System.Drawing.Color.White;
date_Error_cell.Text = "";
bind_grid();
Monthly_Spend();
}
}
else
{
date_Error_cell.Text = "Select a VALID date";
}
}
推荐答案
使用 ^ ]或 DateTime.TryParseExact [ ^ ]而不是Parse的方法-它们如果可能的话,进行转换,并返回bool值以指示成功或失败,而不会抛出异常.
Use DateTime.TryParse[^] or DateTime.TryParseExact[^] methods instead of Parse - they do the conversion if they can, and return a bool value to indicate success or failure without throwing exceptions at all.
在您的文本框中,使用正则表达式进行日期检查;
使用以下验证表达式
In your textbox use regular expression for date check;
with the below validation expression
Copy Code(0[1-9]|[12][0-9]|3[01]).(0[1-9]|1[012]).\d{4}
这篇关于检查日期是否为真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文