Converting a string to a DateTime with more than 7 decimals of milliseconds

So I am trying to convert a string date in the following format to a DateTime. I am able to parse it using ParseExact when there are 7 decimals of fractions of a second using the format string "fffffff", but the string I'm getting can (doesn't always) have 9 decimals of fractions of a second.

I don't really care what those last few digits are as I'm going to end up rounding it anyways. What I'm looking for is some way to either parse them or truncate them before I get an error from the ParseExact method because it doesn't match up with "fffffff". My only thought would be to truncate the string based on the number of characters after the decimal point. Is there an easier way to do this? Thanks in advance!

Sample string to parse: "2015-12-10 13:14:15.123456789"

DateTime.ParseExact("2015-12-10 13:14:15.123456789", "yyyy-MM-dd HH:mm:ss.fffffff", System.Globalization.CultureInfo.InvariantCulture);

throws a FormatException, but the following works.

DateTime.ParseExact("2015-12-10 13:14:15.1234567", "yyyy-MM-dd HH:mm:ss.fffffff", System.Globalization.CultureInfo.InvariantCulture);
Jon Skeet
people
quotationmark

I don't believe you can do this with the normal parsing code and the existing text. DateTime's precision only goes down to ticks, where a tick is 100 nanoseconds. I think the simplest thing to do is truncate the string itself:

string pattern = "yyyy-MM-dd HH:mm:ss.fffffff";
if (text.Length > pattern.Length)
{
    text = text.Substring(0, pattern.Length);
}
DateTime value = DateTime.ParseExact(text, pattern, CultureInfo.InvariantCulture);

Obligatory plug: in Noda Time 2.0 you won't need to do this as it supports a precision of nanoseconds :)

people

See more on this question at Stackoverflow