FileHelpers library - Is it possible to change field's date format at runtime?

1.4k views Asked by At

Using FileHelpers library version 3.0.1 .

Say you define a field to import from a csv file like this :

    [FieldTrim(TrimMode.Both)] 
    [FieldQuoted('"', QuoteMode.OptionalForBoth, MultilineMode.NotAllow)]
    [FieldConverter(ConverterKind.Date, "d-MMMM-yyyy")]
    public DateTime DOB;

Now, the csv field is expected to be in the date format "d-MMMM-yyyy", and set at compile time. I have a requirement at runtime to (sometimes) change this format to "d-MMMM-yy".

The format to use depends on the source file - some files have 2 digit years, others have 4 digit years. I will know at program startup which format to use.

Is this possible with FileHelpers ? I suppose I could add a string column like :

[FieldTrim(TrimMode.Both)] 
[FieldQuoted('"', QuoteMode.OptionalForBoth, MultilineMode.NotAllow)]
public string DOBAsString; 

, and get FileHelpers to read the data into this field, and convert it to the DOB field myself in a loop. Is there a cleaner way ?

1

There are 1 answers

0
shamp00 On BEST ANSWER

The easiest way would be to use the ConverterKind.DateMultiFormat instead of ConverterKind.Date

[FieldTrim(TrimMode.Both)] 
[FieldQuoted('"', QuoteMode.OptionalForBoth, MultilineMode.NotAllow)]
[FieldConverter(ConverterKind.DateMultiFormat, "d-MMMM-yyyy", "d-MMMM-yy"]
public DateTime DOB;

In general, another way of specifying the format at runtime is to use the runtime classes with a ClassBuilder:

FixedClassBuilder cb = new FixedLengthClassBuilder("Customers"); 

cb.AddField("DOB", 8, typeof(DateTime)); 
cb.LastField.Converter.Kind = ConverterKind.Date; 
cb.LastField.Converter.Arg1 = "d-MMMM-yyyy"; // or whatever
cb.LastField.TrimMode = TrimMode.Both; 
cb.LastField.FieldNullValue = DateTime.Now;          

engine = new FileHelperEngine(cb.CreateRecordClass());