FieldConverter ConverterKind.Date “dd/MM/yyyy” exception

元气小坏坏 提交于 2019-12-05 11:00:14

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);
Brosto

What happens when you try:

DateTime.TryParseExact(from, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);

What if write:

[FieldConverter(ConverterKind.Date, "dd'/'MM'/'yyyy")]
public DateTime datum_5;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!