0

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?

TOlsen
  • 45
  • 1
  • 2
  • 8

2 Answers2

2

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;
0

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"
}
John
  • 15,990
  • 10
  • 70
  • 110
  • If the datetime isn't null, but instead is getting set as the `DateTime.MinValue` would it make sense to do something like `if (from.ToString() == DateTime.MinValue.ToString()) { return "00000000"; }` – TOlsen Jul 11 '13 at 19:30
  • Sure -- handle whatever edge cases you need to handle. I'd add a case like `if date field is DateTime.MinValue then return "00000000"` but there is of course more than one way to do it. – John Jul 11 '13 at 21:28