Since DateTime can have many different format styles, I would just use a DateTimeConverter than try to recreate it in a generic method.
Edit
I did a bit of ILspying, and this is what I concluded (happy that you were corrected at any time).
GetCoverter(typeof(DateTime)) will return a DateTimeConverter , so calling CanConvertFrom actually calls DateTimeConverter.CanConvertFrom . CanConvertFrom calls base.CanConvertFrom ( base as the parent class of TypeConverter).
The base.CanConvertFrom method is as follows
public virtual bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(InstanceDescriptor); }
Since DateTime.GetType() != typeof(InstanceDescriptor) , the return value is false . CanConvertFrom is called by the IsValid method, and since we just set the return value to false , IsValid returns false .
So, how does the Convert method work, although the same CanConvertFrom method CanConvertFrom called?
Well, the parameter you pass is of type string , not DateTime .
typeConverter.CanConvertFrom(typeof(string))
In the first code snippet above, the CanConvertFrom method refers to the TypeConverter base class. If we look at DateTimeConverter.CanConvertFrom override, it looks like
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); }
Since we pass string as a type, this method returns true (as opposed to calling IsValid ). Since this returns true, the code continues to call
return (T)typeConverter.ConvertFrom(s);
(where T is a DateTime )
DateTimeConverter simply calls DateTime.Parse and ignores the culture. I'm not sure if this is a design or bug, but I would not rely on DateTime.Parse if you don't know that the string is always the same format (or you format it correctly before calling your method).