【发布时间】:2014-03-22 06:43:10
【问题描述】:
Label gdate=(Label)(GridView1.Rows[i].FindControl("Date"));
现在我想要确保变量 gdate 中的日期(或值)是一个有效的日期(短日期,如 14-03-2014)没有时间(不像 14-03-2014 00:00:00 这是无效)
【问题讨论】:
Label gdate=(Label)(GridView1.Rows[i].FindControl("Date"));
现在我想要确保变量 gdate 中的日期(或值)是一个有效的日期(短日期,如 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 也会抛出异常。
【讨论】:
14-03-2014 00:00:00 并且TryParseExact 仅检查dd-MM-yyyy,它肯定不会解析。究竟是什么不工作?
out dateValue 是 c# 中所谓的 out 参数。当 TryParseExact() 成功解析您提供给它的字符串时,它会创建一个 DateTime 对象并将其放入dateValue。现在,当您向此函数提供 "14-03-2014" 时,它会正确解析,并且 dateValue 现在将包含一个代表 2014 年 3 月 14 日的 DateTime 对象。现在,这个创建的对象也将有小时分钟和秒全为零,因为这些是它们的默认值值。
这里有一个 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);
【讨论】: