开发者

C# String to DateTime

DateTime frm_datestart = DateTime.Parse(dateStart.Text);

This line throws the error:

Exceptio开发者_如何学JAVAn Details: System.FormatException: String was not recognized as a valid DateTime.

Where the entered string is from Jquery-UI, examples:

 09/29/2010
 09/30/2010

Anyone know what the correct format should be? I'm suprised this isn't working :S


You can use an overloaded version of the DateTime.Parse() method which accepts a second DateTimeFormatInfo parameter.

System.Globalization.DateTimeFormatInfo dti = new System.Globalization.DateTimeFormatInfo();
dti.ShortDatePattern = "MM/dd/yyyy";
DateTime dt = DateTime.Parse(dateStart.Text, dti); 


look for DateTime.ParseExact method.


val = dateStart.Text.ToString("yyyy-M-d HH:mm:ss");


Use DateTime.ParseExact to specify format like this: DateTime.Parse("dd/MM/yyyy", dateStart.Text, null)


The problem with DateTime.ParseExact() method suggested in previous answers is, it fails on some Cultures. So your application may fail to run correctly on certain Operating Systems.

If you are sure that dateStart.Text will always be in the same format (i.e. en-US), you may try passing appropriate CultureInfo as a second argument. For format "MM/dd/yyyy" use CultureInfo.InvariantCulture.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜