(DateTime) or DateTime.Parse ?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi All

I wonder what is better to use: (DateTime) or DateTime.Parse

Thanks
Kind regards
Krzysztof Kazmierczak
 
Krzysztof Kazmierczak said:
I wonder what is better to use:
(DateTime) or DateTime.Parse?

(DateTime) will cast an object of some other type to DateTime. This is
probably not very useful in practice, because you cannot cast other basic
types (such as string) to DateTime.

object obj = new DateTime(2004, 4, 4);
DateTime dt = (DateTime) obj;

DateTime.Parse (or DateTime.ParseExact) will attempt to convert a string to
a DateTime. It will throw an exception if the string doesn't look like a
date, so you need to consider what is a valid date string in your locale
(see the .NET documentation).

DateTime dt = DateTime.Parse("2004/04/04");

There is an overload for this function that accepts an IFormatProvider
argument, which gives you more control over the kinds of strings it will
accept.

P.
 
Dear Paul

Thanks for your answer ;) It's all clear now ;

Kind regards
Krzysztof Kazmierczak
 
Back
Top