2015-08-20 22 views
1

我有一个带有AJAX日历扩展控件的aspx文本框。在asp.net中转换后验证日期格式

<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> 

在文本框中输入的日期是“Tue 08/04/2015 12:00:00 AM”格式。我将日期转换为MM/dd/yyyy hh:mm:ss tt格式,使用下面的代码提交按钮单击事件。

CultureInfo ci = new CultureInfo("en-US"); 
DateTime date = Convert.ToDateTime(tbxFirstReceivedDate.Text, ci); 

我想验证转换发生后的日期格式。如果新的日期格式不是MM/dd/yyyy hh:mm:ss tt,我想显示一条错误消息。

如何检查背后的代码格式?

+0

我觉得这以前有人问:http://stackoverflow.com/questions/371987/validate-a-datetime-in-c-sharp。 'DateTime.TryParse'也有一个用于指定格式的可选参数。这有帮助吗? – hschne

+0

“转换发生后我想验证日期格式”是什么意思?转换格式是您要转换的格式。 'DateTime'没有格式,所以一旦你转换了,就没有格式了,它只是一个'DateTime'。 –

回答

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 

}