我有一个带有AJAX日历扩展器控件的aspx文本框。
eA
在文本框中输入的日期位于"星期二08/04/2015 12:00:00 AM"格式。我在提交按钮点击事件中使用以下代码将日期转换为MM / dd / yyyy hh:mm:ss tt格式。
<asp:TextBox ID="tbxFirstReceivedDate" CssClass="selectstyle" runat="server" MaxLength="100" Width="200"></asp:TextBox>
<cc1:CalendarExtender ID="CalendarExtender1" TargetControlID="tbxFirstReceivedDate" BehaviorID="behaviorID" runat="server" Format="ddd MM/dd/yyyy hh:mm:ss tt"></cc1:CalendarExtender>
我想在转换发生后验证日期格式。如果新的日期格式不是MM / dd / yyyy hh:mm:ss tt,我想显示错误信息。
如何检查后面代码的格式?
答案 0 :(得分:0)
DateTime.TryParseExact
允许这样做,如下所示:
var dateString = tbxFirstReceivedDate.Text;
var date format = "MM/dd/yyyy hh:mm:ss tt";
DateTime theDateTime;
if (!DateTime.TryParseExact(dateString, dateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out theDateTime))
{
// Report error about invalid date format here
}