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

purpose

Convert DateTime

to string

using the Oracle [1] datetime format, such as "IY-IW".

Description

I have a situation where I am presented with a format string DateTime

and Oracle date format. The result should be string

one containing the date and time in the format specified by the Oracle date format.

In short, I 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 making a database query, I would use Oracle's to_char method. However, I need to do the conversion in C # environment.

The above questions are on the right track but still don't provide a solution to my problem. For example, providing DateTime.ParseExact in "IY-IW" format throws a FormatException.

Is there an easy way to achieve this goal? Like using DateTime.ParseExact and somehow indicating that the Oracle date format is being used? Or convert Oracle datetime format to C # datetime format in some way [2]?

If so, what would this solution look like?

Notes and links

+3


source to share


2 answers


Is there an easy way to achieve this goal?

Almost certainly not.

How do I use DateTime.ParseExact and somehow indicate that the Oracle date format is being used?

No..NET is not aware of the Oracle date and time format.



Converting Oracle date and time format to C # date and time format in some way?

This 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 little more flexible, I would not support everything that Oracle supports
  • Perhaps you are still facing significant problems around IW

    or other weekly formats. ( DateTime

    does not support ISO weekdays.)

However, I would try to eliminate this requirement in the first place. Whenever possible, try to avoid encoding dates as strings in the first place - if you are specifying a date in the database, specify it as DateTime

or DateTimeOffset

via a parameter. We don't know enough about your context to know if this is an option, but it's worth spending a little time trying to remove this requirement if you can.

+3


source


string oracleDateString = dateTimeToConvert.ToString(oracleDateFormat);

      



0


source







All Articles