-3

I want to cast in C# a String to DateTime.

My String contains: String input = "2012-07-31T00:00:00.000+0200"

and i used the following pattern: String datePattern = "yyyy-MM-dd%HH:mm:ss.fffz";

MyDateTime myDate = new DateTime();
MyDateTime myDate = DateTime.ParseExact(input, datePattern, null);

And i am getting the following error: String was not recognized as a valid DateTime.

Was pretty sure, because i am not sure how to solve this 'T'and which Timezone i should use. There are three variants of it at the msdn side.

Which one i need to use, or can i create my own one? Any suggestions?

Leviathan
  • 282
  • 2
  • 12

1 Answers1

2

You can use The "K" Custom Format Specifier with "yyyy-MM-ddTHH:mm:ss.FFFK" format like;

string s = "2012-07-31T00:00:00.000+0200";
var date = DateTime.ParseExact(s, "yyyy-MM-dd'T'HH:mm:ss.FFFK", CultureInfo.InvariantCulture);
Console.WriteLine(date);

Output will be;

7/30/2012 10:00:00 PM

Here a demonstration.

For more information take a look at;

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364