Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime TypeConverter

I have the below code to convert a string to the type T. It works fine for all other types but gives an error when T is of type DateTime.

TypeConverter c = TypeDescriptor.GetConverter( typeof (T) );
 return (T) c.ConvertTo( obj, typeof (T) )

I pass in a string like

obj =  "09/09/2009"

It throws an error {"'DateTimeConverter' is unable to convert 'System.String' to 'System.DateTime'."}

like image 484
user99322 Avatar asked Sep 02 '25 04:09

user99322


1 Answers

If you know you're getting a string, you can use TypeConverter.ConvertFromString instead. That works with DateTimeConverter, although I don't know why ConvertTo doesn't.

For instance, this works:

TypeConverter c = TypeDescriptor.GetConverter( typeof (DateTime) );
Console.WriteLine((DateTime) c.ConvertFromString("09/09/2009"));

Alternatively, just ConvertFrom works as well:

TypeConverter c = TypeDescriptor.GetConverter( typeof (DateTime) );
Console.WriteLine((DateTime) c.ConvertFrom("09/09/2009"));

It's going to convert to a DateTime because that's the kind of converter it is.

You should be careful of cultural issues though.

like image 110
Jon Skeet Avatar answered Sep 04 '25 17:09

Jon Skeet