I'm having a weird validation failure in a ASP.NET MVC 3 site with a textbox that accepts a datetime choosen via jqueryui. The site has been customized to work only with es-ES culture and works most of the time but the validation fails everytime certain month is used in that textbox. The datetime.parse method works for every month except march:
DateTime.Parse("15-feb-2012",CultureInfo.GetCultureInfo("es"), DateTimeStyles.None)
{15/02/2012 0:00:00}
Date: {15/02/2012 0:00:00}
DateTime.Parse("15-ene-2012",CultureInfo.GetCultureInfo("es"), DateTimeStyles.None)
{15/01/2012 0:00:00}
Date: {15/01/2012 0:00:00}
DateTime.Parse("15-abr-2012",CultureInfo.GetCultureInfo("es"), DateTimeStyles.None)
{15/04/2012 0:00:00}
Date: {15/04/2012 0:00:00}
...
every month works except March , Marzo in Spanish ...
DateTime.Parse("15-mar-2012",CultureInfo.GetCultureInfo("es"), DateTimeStyles.None)
DateTime.Parse("15-mar-2012",CultureInfo.GetCultureInfo("es"), DateTimeStyles.None)' threw an exception of type 'System.FormatException'
base {System.SystemException}: {"String was not recognized as a valid DateTime."}
Any idea?
Reproducing with NUnit:
[Test]
[ExpectedException(typeof(FormatException), ExpectedMessage = "String was not recognized as a valid DateTime.")]
public void ParsingWithAbbreviatedSpanishMarchBlowsUp()
{
var dt = DateTime.Parse("15-mar-2012", CultureInfo.GetCultureInfo("es-ES"), DateTimeStyles.None);
}
Try setting the format and this works:
var format = "dd-MMM-yyyy";
var input= "15-mar-2012";
var dt = DateTime.ParseExact(input, format, new CultureInfo("es-ES"));
Console.WriteLine(dt);
I have the same issue with Italian language.
It was verified only with the .NET 4.0 version and work with 2.0.
Salvo.
ParseExact will do the trick but it requires to refactor a lot of code. Since the problem is caused by not being able to differentiate Marzo and Martes abbreviations. Create a specific culture and modify Martes abbreviation from Mar to Ma like this:
Dim ci As CultureInfo = CultureInfo.CreateSpecificCulture("es-US")
Dim dtfi As DateTimeFormatInfo = ci.DateTimeFormat
dtfi.AbbreviatedDayNames = {"Dom", "Lun", "Ma", "Mie", "Jue", "Vie", "Sab"}
CultureInfo.DefaultThreadCurrentCulture = ci
System.Threading.Thread.CurrentThread.CurrentUICulture = ci
System.Threading.Thread.CurrentThread.CurrentCulture = ci
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With