-5

I have spent a day trying to get DateTime.ParseExact() to work based on this correctly answered question at Parse string to DateTime in C# however, I cannot get the answer to work.

Here is my code:

string testDateRaw = @"2014-05-21 10:08:15.965";
string format = "yyyy-MM-dd H:mm:ss.yyy";
DateTime testDate = DateTime.ParseExact(testDateRaw, format, CultureInfo.InvariantCulture);
System.Console.WriteLine(testDate); 

Error:

DateTime pattern 'y' appears more than once with different values.

Note: error reported in original version of the post does not show up in this sample, but may be related:

"When converting a string to DateTime, parse the string before putting each variable into the DateTime object."

Community
  • 1
  • 1
emailcooke
  • 271
  • 1
  • 4
  • 17
  • 2
    Replace `.yyy` with `.fff` – Ulugbek Umirov Sep 08 '15 at 21:41
  • Congratulation, this the SO's 1,000,000th question on the same topic without reading necessary doc.....https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx BTW: I googled this `datetime custom string` and posted the first link, if you care. – L.B Sep 08 '15 at 21:51

3 Answers3

4

Your format should be yyyy-MM-dd HH:mm:ss.fff

string testDateRaw = @"2014-05-21 10:08:15.965";
string format = "yyyy-MM-dd HH:mm:ss.fff";
DateTime testDate = DateTime.ParseExact(testDateRaw, format, CultureInfo.InvariantCulture);
System.Console.WriteLine(testDate);

See: Custom Date and Time Format Strings

Eser
  • 12,346
  • 1
  • 22
  • 32
4

The error I get with that code is the following:

DateTime pattern 'y' appears more than once with different values.

It's pretty self-explanatory. Looking at the docs, you need to use .fff here:

"yyyy-MM-dd H:mm:ss.fff"

yyy is: The year, with a minimum of three digits, but since you already have yyyy in your pattern, you get the duplicate specifier error.

Lucas Trzesniewski
  • 50,214
  • 11
  • 107
  • 158
1

Your format is wrong, you used y twice.

string testDateRaw = @"2014-05-21 10:08:15.965";
string format = "yyyy-MM-dd H:mm:ss.fff";
DateTime testDate = DateTime.ParseExact(testDateRaw, format, CultureInfo.InvariantCulture);
System.Console.WriteLine(testDate);
Cetin Basoz
  • 22,495
  • 3
  • 31
  • 39