c# - FieldConverter ConverterKind.Date "dd/MM/yyyy" exception -
i try read csv file. fifth record contans date: 03/11/2008
this piece of 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 exception: line: 1. column: 41. field: datum_5. error converting '03/11/2008' type: 'datetime'. using format: 'dd/mm/yyyy'
when this:
[fieldconverter(typeof(convertdate))] public datetime datum_5;
with this:
internal class convertdate : converterbase { /// <summary> /// different forms date separator : . or / or space /// </summary> /// <param name="from">the string format of date - first 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 date " + from, "from"); } }
i got exception: can not make date 03/11/2008 parameternaam: from
what doing wrong?
the reason it's failing / in custom date format string a culture-specific dateseparator described in msdn.
you specifying null
iformatprovider
argument, it's using current culture, presumably has date separator other /.
the best solution explicitly specify cultureinfo.invariantculture (second version below). escaping '/' in custom date format string treated literal slash rather dateseparator work (first version below).
// set current culture culture uses "." dateseparator thread.currentthread.currentculture = new cultureinfo("de-de"); // work - escaping means uses literal / separator datetime.tryparseexact(s, @"dd\/mm\/yyyy", null, datetimestyles.none, out result); // better - culture.invariantculture uses / datetimeformatinfo.dateseparator // , express intent use invariant culture datetime.tryparseexact(s, "dd/mm/yyyy", cultureinfo.invariantculture, datetimestyles.none, out result); // fail - / means use datetimeformatinfo.dateseparator "." in de-de culture datetime.tryparseexact(s, "dd/mm/yyyy", null, datetimestyles.none, out result);
Comments
Post a Comment