Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Oracle Date to c# DateTime

Tags:

date

c#

datetime

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

like image 218
Bagzli Avatar asked May 16 '13 19:05

Bagzli


People also ask

Can we convert a date to char in Oracle?

The Oracle TO_CHAR() function converts a DATE or INTERVAL value to a string in a specified date format. The Oracle TO_CHAR() function is very useful for formatting the internal date data returned by a query in a specific date format.

What is the difference between TO_DATE and TO_CHAR in Oracle?

To_char formats a DATE into a string using the given format mask. To_date converts a STRING into a date using the format mask.

What is the use of TO_CHAR in Oracle?

TO_CHAR (datetime) converts a datetime or interval value of DATE , TIMESTAMP , TIMESTAMP WITH TIME ZONE , or TIMESTAMP WITH LOCAL TIME ZONE datatype to a value of VARCHAR2 datatype in the format specified by the date format fmt .

Why do we use TO_CHAR?

TO_CHAR function is used to typecast a numeric or date input to character type with a format model (optional).


3 Answers

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

like image 168
Maaark Avatar answered Oct 03 '22 16:10

Maaark


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.

like image 38
Alexander Bortnik Avatar answered Oct 03 '22 16:10

Alexander Bortnik


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)

enter image description here

like image 34
Steve's a D Avatar answered Oct 03 '22 16:10

Steve's a D