Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

datetime.parse failing for march in Spanish, every other month works

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?

like image 583
dtriana Avatar asked Jan 17 '12 18:01

dtriana


3 Answers

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);
like image 81
Luke Hutton Avatar answered Nov 02 '22 23:11

Luke Hutton


I have the same issue with Italian language.

It was verified only with the .NET 4.0 version and work with 2.0.

Salvo.

like image 23
Blackat.net Avatar answered Nov 02 '22 23:11

Blackat.net


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
like image 45
Christian Rios Avatar answered Nov 02 '22 23:11

Christian Rios