Dmitriy Sosunov
Dmitriy Sosunov

Reputation: 1113

How to parse this string as a DateTime

How can I parse the following string to DateTime with timezone? Should I use CultureInfo? TimeZoneInfo? Or some other kind?

15.08.11 17:15:18.084867000 +02:00

I have try to use the following format:

var z = DateTime.Now.ToString("dd.MM.yy H:mm:ss.fffffff", CultureInfo.InvariantCulture);

But it threw an exception.

Upvotes: 1

Views: 300

Answers (1)

Binary Worrier
Binary Worrier

Reputation: 51711

DateTime.ParseExact is what you want.

The actual format string you need is dd.MM.yy HH:mm:ss.FFFFFFF00 zzz

var dateTest = "15.08.11 17:15:18.084867000 +02:00";
var format = "dd.MM.yy HH:mm:ss.FFFFFFF00 zzz";
var returnDate = DateTime.ParseExact(dateTest, format, System.Globalization.CultureInfo.InvariantCulture);

The problem is that the fractional portion of seconds can only be 7 digits, and you need to pad the format string with zeros to cater for it.

There is a problem in that the last two digits of the seconds must be 00, otherwise the format won't work, so if the last two digits are ever anything other than 00 this format string won't work for you.

You'd need to parse out the entire string excluding the last to digits of the seconds but keeping the rest of the string intact. If one was to go to that much bother one might be as well off just manually parsing the string.

Sorry I can't be of more help.

Upvotes: 3

Related Questions