Search code examples
c#datetimefilehelpersfixed-length-record

Zero filling null datetimes and formatting datetime


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?


Solution

  • 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"
    }