How to convert DateTime to string in C # using Oracle date format
using the Oracle  datetime format, such as "IY-IW".
I have a situation where I am presented with a format string
and Oracle date format. The result should be
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.
- C # How to parse a date string in an arbitrary given Oracle date format?
- How to format a date from Oracle to a valid datetime in C #
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 ?
If so, what would this solution look like?
Notes and links
- Oracle Date Format Specification: http://www.techonthenet.com/oracle/functions/to_char.php
- Creating a method to map Oracle datetime formats to C # date and time formats would be possible, but I don't find it a good or easy solution.
source to share
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
or other weekly formats. (
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
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.
source to share