[英]Correct Date Format Validation of a Date
Label gdate=(Label)(GridView1.Rows[i].FindControl("Date"));
现在我想要的是确保变量gdate中的日期(或值)是没有时间的有效日期(ShortDate,如14-03-2014 )(不像14-03-2014 00:00:00那样无效 )
如果需要检查确切的格式,请使用DateTime TryParseEaxct
:
DateTime dateValue
if (DateTime.TryParseExact(gdate.Text, "dd-MM-yyyy", null,
DateTimeStyles.None, out dateValue))
{
//Date in correct format
//use dateValue
}
else
{
//Date in incorrect format
}
如果无法解析日期时间,则Convert.ToDateTime
将引发异常。
如果Date
控件中的日期字符串为空,则ParseExact
也将引发异常。
一个CustomValidator在这里:
<asp:CustomValidator runat="server"
ID="valDateRange"
ControlToValidate="txtDatecompleted"
onservervalidate="valDateRange_ServerValidate"
ErrorMessage="enter valid date" />
服务器端:
protected void valDateRange_ServerValidate(object source, ServerValidateEventArgs args)
{
DateTime minDate = DateTime.Parse("1000/12/28");
DateTime maxDate = DateTime.Parse("9999/12/28");
DateTime dt;
args.IsValid = (DateTime.TryParse(args.Value, out dt)
&& dt <= maxDate
&& dt >= minDate);
}
您可以将短日期功能用于日期格式,例如
DateTime dt=new DateTime();
dt = DateTime.Now;
MessageBox.Show(dt.ToShortDateString());
尝试这个
gdate.Text = DateTime.Now.Date.ToShortDateString();
试试这个来存储格式化的日期
string chkin = txtCheckIn.Text;
DateTime CheckIn = DateTime.ParseExact(chkin, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.