Datetime.parse, not past march in Spanish, works every two months

I had a strange validation error on an ASP.NET MVC 3 site with a text field that accepts the date and time selected through jqueryui. The site is configured to work only with the es-ES culture and works most of the time, but the check is not performed every time a specific month is used in this text box. The datetime.parse method works every month, except for the 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?

+5
source share
3 answers

Playback 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 it works:

var format = "dd-MMM-yyyy";
var input= "15-mar-2012";
var dt = DateTime.ParseExact(input, format, new CultureInfo("es-ES"));
Console.WriteLine(dt);
+5
source

I have the same problem with the Italian language.

.NET 4.0 2.0.

.

+1

ParseExact will do the trick, but it requires refactoring a lot of code. Because the problem is caused by the inability to differentiate the cuts of Marzo and Martes. Create a specific culture and change the abbreviation Marta 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
+1
source

All Articles