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'."}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With