Datetime convert

S

SimonZ

Hi,

can someone explain me, when to use:
(DateTime)DataBinder.Eval(Container.DataItem, "dateField")

OR

Convert.ToDateTime(DataBinder.Eval(Container.DataItem, "dateField"))

Sometimes (DateTime) works sometimes not, on the other hand
Convert.ToDateTime() always works.

The same problem is with (int16) and Convert.ToInt16

Thanks,S
 
J

Jon Skeet [C# MVP]

SimonZ said:
can someone explain me, when to use:
(DateTime)DataBinder.Eval(Container.DataItem, "dateField")

OR

Convert.ToDateTime(DataBinder.Eval(Container.DataItem, "dateField"))

Sometimes (DateTime) works sometimes not, on the other hand
Convert.ToDateTime() always works.

The same problem is with (int16) and Convert.ToInt16

When you cast, the runtime type of the object must be exactly correct
(leaving conversion operators aside for the moment as they're not
relevant in your example).

When you use Convert.ToDateTime(object), the object just has to be of
some type which implements IConvertible and does the appropriate thing
with IConvertible.ToDateTime.

In other words, it depends what DataBinder.Eval actually returns. If it
returns a string, for instance, Convert.ToDateTime will work (because
System.String implements IConvertible and tries to parse the string as
a date/time) but casting won't.

Does that help?
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,


An addition to the OP comments, Convert.ToDateTime does not always work,
there are a number (most of them) that raise exception , IIRC only when
received a string it does the conversion.



--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top