Question

I am using JsonConverter attribute to set my datetime format but for the string "yyyyMMddThhmmss.000GMT" I get dates like "19900321T20000.000G3T" because of the latter M. How do I escape these characters in my format string?

Was it helpful?

Solution

You can use:

 "yyyyMMdd'T'HHmmss'.000GMT'"

I changed hh to HH since most (sane) people use a 24-hour count.

On the documentation Custom Date and Time Format Strings it is shown that aopstrophe characters like in 'string' can be used for literal string delimiters. Now I also put the T inside this delimiter, just for clarity, even if one capital T has no other meaning in a DateTime format string.

OTHER TIPS

Use single quote to escape like:

"yyyyMMddThhmmss'.000GMT'"

Like:

string str = "19900321T20000.000GMT";
DateTime dt = DateTime.ParseExact(str,"yyyyMMddTHHmms'.000GMT'", CultureInfo.InvariantCulture);

Change hh to HH for 24 hours, also it appears your seconds are single digit values, so use a single s.

(I assume in your question original string you have GMT, not G3T)

You have 2 options to use your ...GMT part as string literal delimiter in custom date and format string:

  • ".000GMT"
  • '.000GMT'

But I suggest to use single quotes because if you use double quotes, you need to escape your quotes with \ (because of escape sequence) or you can use verbatim string literal.

Do the same thing with T middle in your string as well.

Also use HH specifier which is for 24-hour clock and use s speficier instead of ss because you have 5 digit after your T that's why it doesn't accept HHmmss format.

The reason of you get G3T it is because M is has meaning of month of custom string format and that's why your GMT parsed as G3T.

string s = "19900321T20000.000G3T";
var dt = DateTime.ParseExact(s, "yyyyMMdd'T'HHmms'.000G3T'",
                                 CultureInfo.InvariantCulture);

With double quotes;

string s = "19900321T20000.000G3T";
var dt = DateTime.ParseExact(s, "yyyyMMdd\"T\"HHmms\".000G3T\"",
                                 CultureInfo.InvariantCulture);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top