Convert Oracle Date to c# DateTime
Solution 1
This:
DateTime dateTime = DateTime.ParseExact(ds.Tables[0].Rows[0][0].ToString(), "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
parses using specified format and does not depend on thread culture.
Solution 2
Everyone else is overcomplicating it.
Oracle Managed Data Access (which I assume you're using) returns dates as the "OracleDate" type. OracleDate has a property "Value" which is a c# DateTime.
In my case, to get a DateTime from an out parameter (p2 below), I used
return ((OracleDate) p2.Value).Value;
For Op's case where the date in question is in a row of the returned dataset, use
DateTime dt = (DateTime) ds.Tables[0].Rows[0][0];
edit: if taking data from a DataRow, for some reason the date will actually be a c# DateTime
Solution 3
Any reason you can't just use DateTime.Parse()
? Taking in the database value seemed to give the correct output (with the time included which seems to be what you're after)
Bagzli
Updated on June 11, 2020Comments
-
Bagzli almost 4 years
I am trying to read a record from oracle database of type Date and then convert it to ASP.NET c# DateTime object. Problem is, it picks up the date but not the time. Command I'm using is:
DateTime dt = Convert.ToDateTime(ds.Tables[0].Rows[0][0].ToString());
If I try to print
ds.Tables[0].Rows[0][0].ToString()
then it shows the time as well. Anyone know how to get around this?My oracle date field has a value/format of:
2013-01-01 14:14:14
-
Alexander Bortnik almost 11 yearsDateTime.Parse() is culture-dependant, so it can produce different results for you and @Bagzli
-
Joe Gayetty about 5 yearsI arrived here looking for help getting a C# DateTime from the date returned from OracleCommand.ExecuteScalar(). You pointed me in the right direction. Thanks! My code ended up being thus: DateTime OriginalEntryDate = ((OracleDate)cmd.ExecuteScalar()).Value;