newbie question on casting a DateTime field from datareader

  • Thread starter Thread starter Danny Ni
  • Start date Start date
D

Danny Ni

Hi,

I used SqlDataReader to retrieve a resultset from SQL server. Say the
SqlDataReader name is drEmployee, it has a DateTime field which I like to
convert it to ShortDate format.

I tried: drEmployee["HireDate"].ToShortDateString()
No go. Does not even compile

I tried: drEmployee["HireDate"].ToString()
It's working, but I don't like the time portion.

Seems to me drEmployee["HireDate"] is a System.Object, but how do I cast it
so I can use DateTime's methods?

TIA
 
Danny Ni said:
I used SqlDataReader to retrieve a resultset from SQL server. Say the
SqlDataReader name is drEmployee, it has a DateTime field which I like to
convert it to ShortDate format.

I tried: drEmployee["HireDate"].ToShortDateString()
No go. Does not even compile

I tried: drEmployee["HireDate"].ToString()
It's working, but I don't like the time portion.

Seems to me drEmployee["HireDate"] is a System.Object, but how do I
cast it so I can use DateTime's methods?

Just cast it to DateTime:

DateTime dt = (DateTime) drEmployee["HireDate"];
 
Thank you for the response, that works. Just want to make sure the following
does not work:
(DateTime)drEmployee["HireDate"].ToShortDateString()

Jon Skeet said:
Danny Ni said:
I used SqlDataReader to retrieve a resultset from SQL server. Say the
SqlDataReader name is drEmployee, it has a DateTime field which I like to
convert it to ShortDate format.

I tried: drEmployee["HireDate"].ToShortDateString()
No go. Does not even compile

I tried: drEmployee["HireDate"].ToString()
It's working, but I don't like the time portion.

Seems to me drEmployee["HireDate"] is a System.Object, but how do I
cast it so I can use DateTime's methods?

Just cast it to DateTime:

DateTime dt = (DateTime) drEmployee["HireDate"];
 
"Danny Ni" ...
Just want to make sure the following does not work:
(DateTime)drEmployee["HireDate"].ToShortDateString()

It doesn't, as System.Object doesn't have any method "ToShortDateString".

However, the following should work:

( (DateTime)drEmployee["HireDate"] ).ToShortDateString();

...that is to cast the object to DateTime *before* applying the method.

// Bjorn A
 
Back
Top