How to convert DateTime to string in C# using Oracle date format

Goal

Convert a DateTime to string using an Oracle datetime format[1] like "IY-IW".

Description

I have a situation where I'm provided a DateTime and an Oracle date format string. The result should be a string containing the date and time in the format specified by the Oracle date format.

In short, I would need the method below

/// <summary>
/// Converts a datetime to a string with the format specified by the Oracle date format.
/// </summary>
/// <param name="oracleDateFormat">
/// Datetime format specified in http://www.techonthenet.com/oracle/functions/to_char.php
/// </param>
/// For example:
/// dateTimeToConvert = 2014-09-23T10:09:47.7739125+02:00, oracleNlsDateFormat = "IY-IW" => result == "14-38"
public string ConvertDateTimeToString(DateTime dateTimeToConvert, string oracleDateFormat);

If done in a database query, I would have used the Oracle to_char method. However, I need to do the conversion in the C# environment.

The questions above are on the right track but still doesn't give a solution to my problem. For instance, providing DateTime.ParseExact with the format "IY-IW" raises a FormatException.

Is there a simple way to achieve the goal? Like using DateTime.ParseExact and somehow specifying that an Oracle date format is used? Or converting the Oracle datetime format to C# datetime format on some way[2]?

If yes, how would that solution look like?

Notes and references

  1. The Oracle date format specification: http://www.techonthenet.com/oracle/functions/to_char.php
  2. Creating a method mapping Oracle datetime formats to C# datetime formats would be possible but I don't consider it being a good or simple solution.
Jon Skeet
people
quotationmark

Is there a simple way to achieve the goal?

Almost certainly not.

Like using DateTime.ParseExact and somehow specifying that an Oracle date format is used?

No - .NET doesn't know about the Oracle date/time format.

Converting the Oracle datetime format to C# datetime format on some way?

That would be my first suggestion. In particular:

  • If you only need to support a small number of these formats, it may be worth hard-coding the ones you support
  • Even if you need to be a bit more flexible than that, I wouldn't try to support everything Oracle supports
  • You may well still run into significant issues around IW or other week-based formats. (DateTime doesn't support ISO week-years.)

I would attempt to remove the requirement in the first place, however. Wherever possible try to avoid encoding dates as strings in the first place - if you're providing a date to the database, provide it as a DateTime or DateTimeOffset via a parameter. We don't know enough about your context to know whether or not that's an option, but it's worth spending a bit of time trying to remove the requirement if you can.

people

See more on this question at Stackoverflow