Home > Enterprise >  Parsing Oracle Date to C# datetime
Parsing Oracle Date to C# datetime

Time:02-02

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.

CodePudding user response:

Try

d-MMM-yy h.m.s.ffffff'000' tt

format string. I.e.

var result = DateTime.ParseExact(
  "22-FEB-21 09.52.41.256898000 AM", 
  "d-MMM-yy h.m.s.ffffff'000' tt", 
   CultureInfo.InvariantCulture);

Format explained:

 d      - day in one ore two digit format
 MMM    - month (abbreviation)
 yy     - year (two digits)
 h      - hour 1..12 or 01..12
 m      - minutes 00..59 or 0..59
 s      - seconds 00..59 or 0..59
 ffffff - fraction of seconds
'000'   - 000
 tt     - AM or PM 

CodePudding user response:

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:

"dd-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",
   "dd-MMM-yy hh.mm.ss.fffffff'00' tt", CultureInfo.InvariantCulture);
Console.WriteLine(date);

That should solve your problem.

  •  Tags:  
  • Related