Erik Kinding
Erik Kinding

Reputation: 1870

Parsing timestamp containing special characters (quotes)

So, the other day I ran into a problem when trying to parse a timestamp which was wrapped in quotes, it looked like this in the file I was reading:

"2018-04-09"

A C# string with this content:

var dt = "\"2018-04-09\""

I wanted to use DateTime.TryParseExact() to convert the string into a .net DateTime object, without stripping the chars from the string (don't ask why, it's not relevant), but finding a working format string turned out to be tricky.

I read the docs. I googled. Searched StackOverflow. No success.

What format would allow me to parse this timestamp to a DateTime object?

Upvotes: 1

Views: 298

Answers (1)

Erik Kinding
Erik Kinding

Reputation: 1870

So - the solution, handed to me by a colleague:

var format = "\\\"yyyy-MM-dd\\\"";

If I understand this correctly, the format string is expected to contain a \ which is later resolved to escape the " inside ParseExact(). The first \ escapes the second, the third escapes ", leading to the character sequence \" as part of the format string which is then processed somewhere down the line.

The following works:

var dts = "\"2018-04-09\"";
var format = "\\\"yyyy-MM-dd\\\"";
var dt = DateTime.ParseExact(dts, format, null);

I hope this helps someone!

Upvotes: 1

Related Questions