Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse string with long milliseconds (nanoseconds) part to DateTime?

I'm trying to figure-out the right string format of the following given date-time literal:

18-JUN-13 12.17.36.000000000

Using MSDN, I managed to composed the following format:

"d'-'MMM'-'y'T'h'.'m'.'s'.'fff"

But when using the DateTime.ParseExact, the parsing fails with a FormatException: String was not recognized as a valid DateTime.

My code:

DateTime.ParseExact("18-JUN-13 12.17.36.000000000", "d'-'MMM'-'y'T'h'.'m'.'s'.'fff", null);
like image 515
Yair Nevet Avatar asked Sep 29 '22 19:09

Yair Nevet


1 Answers

You can use

dd-MMM-yy hh.mm.ss.fffffff

with english based culture like InvariantCulture for example. I'm on mobile right now, so I can't try it :(

AFAIK, milliseconds part parsing limit is 7, that's why you can't parse your string without manipulate it. You can use it like;

var dt = DateTime.ParseExact("18-JUN-13 12.17.36.0000000",
                             "dd-MMM-yy HH.mm.ss.fffffff",
                             CultureInfo.InvariantCulture);

Looks like that's why probably we have The "fffffff" custom format as top character of milliseconds. From docs;

Although it is possible to display the ten millionths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On the Windows NT 3.5 (and later) and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.

You asked;

How would you have manipulate the string?

Well, one way to get last index of comma and substring it to 8 index after that like;

string s = "18-JUN-13 12.17.36.000000000";
var dateString = s.Substring(0, s.LastIndexOf(".") + 8);
like image 114
Soner Gönül Avatar answered Oct 03 '22 08:10

Soner Gönül