DateTime TypeConverter

I have the code below to convert a string to 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 a string like

obj =  "09/09/2009"

It gives an error message {"DateTimeConverter" cannot convert "System.String" to "System.DateTime". "}

+3
source share
1 answer

If you know you are getting a string, you can use TypeConverter.ConvertFromString. This works with DateTimeConverter, although I do not know why ConvertToit does not.

For example, this works:

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

As an alternative, only works ConvertFrom:

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

DateTime, .

.

+7

Source: https://habr.com/ru/post/1713388/


All Articles