Question

I'm trying to write a fixed length file with FileHelpers. A few of the fields I have are datetimes that can be null values. If they are null values I need them to be zero filled (i.e. "00000000" instead of the date). I tried using a custom field converter,

public class CustomDateConverter : ConverterBase
{
    public override object StringToField(string from)
    {
        if (from == null)
        {
            return string.Empty;
        }
        return from;
    }
}

but the issue is I need this date in a specific format. I can achieve the format using

[FieldConverter(ConverterKind.Date, "MMddyyyy")]

But then I can't use my customer field converter.

Could someone please steer me straight on how I accomplish both the format conversion and zero filling the null values I might get?

Was it helpful?

Solution 2

For your purposes (writing the file) the field is an eight-digit string, so treat it as such, and only use the date conversions as an intermediate step to producing an eight-digit string.

So something like this (pseudocode):

if date field is null
{
    return "00000000"
}
else
{
    return string of date formatted as "MMddyyyy"
}

OTHER TIPS

Try this:

public class CustomDateConverter : ConverterBase
{
    public override object StringToField(string stringValue)
    {
        if (string.IsNullOrEmpty(stringValue) || stringValue == "00000000")
        {
            return null;
        }

        return Convert.ToDateTime(stringValue);
    }

    public override string FieldToString(object fieldValue)
    {
        return fieldValue == null ? "00000000" : ((DateTime)fieldValue).ToString("MMddyyyy");
    }
}

[FieldConverter(typeof(CustomDateConverter))]
public DateTime? MyDate;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top