留空时的日期问题。 [英] Date problems when leaving blank.
本文介绍了留空时的日期问题。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
string dateToformat = DD / MM / YYYY跨度>;
DateTime dateTo = DateTime.ParseExact(tb_DateTo.Text,dateToformat,CultureInfo.InvariantCulture);
if (dateFrom == default (DateTime))
{
returnMessage + = Date From不能为空!< br /> ;
}
如果我将日期留空,则会出现错误,但字符串不是公认的日期时间。我不确定。请帮忙。谢谢。
解决方案
使用string.IsNullOrEmpty将有助于检查是否有任何文本。你甚至可以使用.Trim()
DateTime dateFrom;
if ( string .IsNullOrEmpty(tb_DateFrom.Text.Trim()) )
{
msg1 + = Date From不能为空!< br /> 跨度>;
}
else
{
string dateFromformat = dd / MM / yyyy;
dateFrom = DateTime.ParseExact(tb_DateFrom.Text,dateFromformat,CultureInfo.InvariantCulture);
}
你也可以使用DateTime.TryParse(dateString,out convertDateTime);
在验证或使用日期时,总是应该在转换之前进行验证。
if ( string .IsNullOrEmpty(tb_DateTo.Text.Trim()))
{
returnMessage + = To Date不能为空!;
}
if ( string .IsNullOrEmpty(dateFrom.Trim ()))
{
returnMessage + = Date From不能为空!跨度>;
}
// 后续步骤
string dateToformat = "dd/MM/yyyy";
DateTime dateTo = DateTime.ParseExact(tb_DateTo.Text, dateToformat, CultureInfo.InvariantCulture);
if (dateFrom == default(DateTime))
{
returnMessage += "Date From cannot be blank! <br />";
}
There is an error, if I left blank my date from, it will have string was not a recognized datetime. I am not sure. Please help. Thanks.
解决方案
Using string.IsNullOrEmpty will help check if there is any text. you can even use .Trim()
DateTime dateFrom; if (string.IsNullOrEmpty(tb_DateFrom.Text.Trim())) { msg1 += "Date From cannot be blank! <br />"; } else { string dateFromformat = "dd/MM/yyyy"; dateFrom = DateTime.ParseExact(tb_DateFrom.Text, dateFromformat, CultureInfo.InvariantCulture); }
you can also use DateTime.TryParse(dateString, out convertDateTime);
When validating or working with datetimes always should be validate before converting.
if (string.IsNullOrEmpty(tb_DateTo.Text.Trim())) { returnMessage += "To Date cannot be blank!"; } if (string.IsNullOrEmpty(dateFrom.Trim())) { returnMessage += "Date From cannot be blank!"; } //next steps
这篇关于留空时的日期问题。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文