简体   繁体   中英

Getting an error while converting string to DateTime

I am trying to convert a string value into DateTime. It gives me an error as, specified string is not in correct format.

Here is the code,

DateTime myDate = DateTime.ParseExact("07-09-2013 01:14:14:1414", "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
string strDate = "07/09/2013 01:04:02:4";
Convert.ToDateTime(strDate); 
DateTime dt = DateTime.Parse(strDate);

Please help in converting the same.

Thanks

Your format seems to be incorrect. Should be:

"dd-MM-yyyy HH:mm:ss:ffff"

Update. If number of digits representing fractions of a second varies, than the best bet is

"dd-MM-yyyy HH:mm:ss:FFFFFFF"

Refer to MSDN for other options for custom time and date formats.

Your format isn't correct: " 07-09-2013 01:14:14:1414" " yyyy-MM-dd HH:mm:ss"

Atleast your date is the other way around, and the milliseconds is not specified. Correct you format according to this: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

For the downvoter: The correct format is specified by Andrei: "dd-MM-yyyy HH:mm:ss:ffff"

Try in your page_load event:

Thread.CurrentThread.CurrentUICulture = New System.Globalization.CultureInfo("tr-TR")
Thread.CurrentThread.CurrentCulture = New System.Globalization.CultureInfo("tr-TR")

First, you mixed you years place

07-09-2013 is dd-MM-yyyy format

second, you need a :ffff after seconds

So the final line should be

DateTime myDate = DateTime.ParseExact("2013-07-09 01:14:14:1414", "yyyy-MM-dd HH:mm:ss:ffff", System.Globalization.CultureInfo.InvariantCulture);

First of all, you should change your date format to dd-MM-yyyy because it fits with your date format.

Second of all, for miliseconds part, you can use . instead of :

DateTime myDate = DateTime.ParseExact("07-09-2013 01:14:14.1414", "dd-MM-yyyy HH:mm:ss.ffff", System.Globalization.CultureInfo.InvariantCulture);
string strDate = "07/09/2013 01:04:02.4";
Convert.ToDateTime(strDate);
DateTime dt = DateTime.Parse(strDate);

Here a DEMO .

For more information, check Custom Date and Time Format Strings

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM