Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing strings in custom formats using TypeConverter.ConvertFromString()

Using TypeConverter.ConvertFromString(), I need to supply a custom format when parsing data from a string (for example, with DateTime: "ddMMyyyy" or "MMMM dd, yyyy").

TypeConverter.ConvertFromString() has the following overload:

public object ConvertFromString(ITypeDescriptorContext context, 
                                CultureInfo culture, 
                                string text);

I checked up on MSDN about ITypeDescriptorContext.

The ITypeDescriptorContext interface provides contextual information about a component. ITypeDescriptorContext is typically used at design time to provide information about a design-time container. This interface is commonly used in type conversion.

This sounds like what I need to use but I cannot find any examples anywhere.

I am using the following generic method:

public T ParseValue<T>(string value)
{
    return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(value);
}

Example calling code:

DateTime date = ParseValue<DateTime>("02062001");
decimal amount = ParseValue<decimal>("1.3423");

I want to be able to parse some kind of generic formatting info into this ParseValue() method which can be used by ConvertFromString().

like image 495
Dave New Avatar asked Apr 24 '13 13:04

Dave New


1 Answers

You can create a custom CultureInfo , holding your format.

Another solution would be to Wrap conversion in some helper method that would use DateTime.Parse for dates and TypeConverter for other types.

like image 60
alex Avatar answered Oct 18 '22 20:10

alex