1,winform
[csharp]
#region 日歷控件
private void dteStartDate_Validating(object sender, CancelEventArgs e)
{
if (!CheckStartDateEndDate(true))
{
XtraMessageBox.Show("起始日期不能大於結束日期");
dteStartDate.Focus();
e.Cancel = true;
}
}
private void dteEndDate_Validating(object sender, CancelEventArgs e)
{
if (!CheckStartDateEndDate(false))
{
XtraMessageBox.Show("結束日期不能小於起始日期");
dteEndDate.Focus();
e.Cancel = true;
}
}
#endregion
private bool CheckStartDateEndDate(bool bLeaveFromStartDate)
{
if (!(string.IsNullOrEmpty(dteStartDate.Text) || string.IsNullOrEmpty(dteEndDate.Text)))
{
if (Convert.ToDateTime(dteStartDate.Text) > Convert.ToDateTime(dteEndDate.Text))
{
if (bLeaveFromStartDate)
{
return false;
}
else
{
return false;
}
}
}
return true;
}
2,web
[csharp]
if (txtStartDate.Value==null || !PageValidate.IsDateTime(txtStartDate.Value.ToString()))
strErr+="請輸入正確的開始日期!\\n";
if (txtEndDate.Value == null || !PageValidate.IsDateTime(txtEndDate.Value.ToString()))
strErr += "請輸入正確www.2cto.com的結束日期!\\n";
if(Convert.ToDateTime(txtStartDate.Value.ToString()).CompareTo(Convert.ToDateTime(txtEndDate.Value.ToString()))>0)
{
strErr += "開始時間不能大於結束時間!\\n";
}
#region 日期格式判斷
/// <summary>
/// 日期格式字符串判斷
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool IsDateTime(string str)
{
try
{
if (!string.IsNullOrEmpty(str))
{
DateTime.Parse(str);
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
}
#endregion
摘自keenweiwei的專欄