I'm currently reading DateTime items from an Oracle database, which are in the format dd/mm/yyyy hh:mm:ss, but I need them to be stored as follows: yyyy-mm-dd hh:mm:ss.
I've tried two approaches. The first I've tried splits a string version of the date into parts and reassembles it to give me the output I desire. However, converting this to a DateTime object reverts it to the original format. Here's the code:
public static DateTime FormatDateTimeForPDB(string dateTimeString)
{
DateTime formattedDateTime;
char[] illegals = { '/', ' ', ':' };
string[] array = dateTimeString.Split(illegals);
string date = array[2] + "-" + array[1] + "-" + array[0] + " " + array[3] + ":" + array[4] + ":" + array[5];
formattedDateTime = Convert.ToDateTime(date);
return formattedDateTime;
}
A breakpoint at Convert.ToDateTime(date) shows date as 2012-09-07 15:01:03 which is the format I want, but as a string, not a DateTime.
I've also tried using the DateTimeFormatInfo attribute as discussed by the user tatis over here, but all that managed to do was swap the month and day fields (giving me mm/dd/yyyy hh:mm:ss). Any help would be greatly appreciated.
If you are worried about parsing the date string into a DateTime in C# take a look at DateTime's ParseExact method. Documentation here.
Something like this:
CultureInfo provider = CultureInfo.InvariantCulture;
String format = "dd/MM/yyyy hh:mm:ss";
return DateTime.ParseExact(dateString, format, provider);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With