'Parsing Oracle Date to C# datetime

I need to Parse the following string as a DateTime in c#:

"22-FEB-21 09.52.41.256898000 AM"

I've tried the following but it throws exception:

DateTime.ParseExact(
  "22-FEB-21 09.52.41.256898000 AM",
  "DD-MON-YY HH.mm.ss.ff AM", 
   CultureInfo.InvariantCulture);

The exception being thrown is

String was not recognized as a valid DateTime.



Solution 1:[1]

There are a couple of problems with your date string. First, are you sure you are getting 9 decimal places? Since Oracle only supports 6 decimals of precision, maybe you can do something on the query side to remove those?

Also your format string has some problems.

  1. It should be MMM not MON for the month
  2. It should be hh since you are using a 12 hour clock standard (AM/PM) and not 24 hours.

Then you need to fix your fractional seconds, and use a string match for the last two zeros. Your format string ends up to be:

"d-MMM-yy hh.mm.ss.fffffff'00' tt"

So to test it, you can run this:

var date = DateTime.ParseExact(
   "22-FEB-21 09.52.41.258998000 AM",
   "d-MMM-yy hh.mm.ss.fffffff'00' tt", CultureInfo.InvariantCulture);
Console.WriteLine(date);

That should solve your problem.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1