Search code examples
c#.netdatetimecsvfilehelpers

FieldConverter ConverterKind.Date "dd/MM/yyyy" exception


I try to read a csv file. my fifth record contans a date: 03/11/2008

This is a piece of my code:

    [FieldConverter(ConverterKind.Date, "dd/MM/yyyy")]
    public DateTime datum_5;

My code crashs on this:

Result[] results= (Result[])engine.ReadFile(@"..\Data\expo.txt");

And with this exception: Line: 1. Column: 41. Field: datum_5. Error Converting '03/11/2008' to type: 'DateTime'. Using the format: 'dd/MM/yyyy'

When i do this:

[FieldConverter(typeof(ConvertDate))]

        public DateTime datum_5;

with this:

internal class ConvertDate : ConverterBase
   {

       /// <summary>
       /// different forms for date separator : . or / or space
       /// </summary>
       /// <param name="from">the string format of date - first the day</param>
       /// <returns></returns>

       public override object StringToField(string from)
       {
           DateTime dt;

           if (DateTime.TryParseExact(from, "dd.MM.yyyy", null, DateTimeStyles.None, out dt))
               return dt;

           if (DateTime.TryParseExact(from, "dd/MM/yyyy", null, DateTimeStyles.None, out dt))
               return dt;

           if (DateTime.TryParseExact(from, "dd MM yyyy", null, DateTimeStyles.None, out dt))
               return dt;

           throw new ArgumentException("can not make a date from " + from, "from");

       }
   }

I got this exception: can not make a date from 03/11/2008 Parameternaam: from

What am i doing wrong?


Solution

  • The reason it's failing is that / in a custom date format string is a culture-specific DateSeparator as described in MSDN.

    You are specifying null for the IFormatProvider argument, so it's using the current culture, which presumably has a date separator other than /.

    The best solution is to explicitly specify CultureInfo.InvariantCulture (second version below). Escaping the '/' in your custom date format string so that it is treated as a literal slash rather than a DateSeparator will also work (first version below).

    // Set current culture to a culture that uses "." as DateSeparator
    Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");
    // This will work - escaping means it uses a literal / as the separator
    DateTime.TryParseExact(s, @"dd\/MM\/yyyy", null, DateTimeStyles.None, out result);
    
    // This is better - Culture.InvariantCulture uses / for the DateTimeFormatInfo.DateSeparator
    // and you clearly express the intent to use the invariant culture
    DateTime.TryParseExact(s, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out result);
    
    // This will fail - / means use DateTimeFormatInfo.DateSeparator which is "." in the de-DE culture
    DateTime.TryParseExact(s, "dd/MM/yyyy", null, DateTimeStyles.None, out result);