views:

1686

answers:

3

I'm working with an ASP.NET app with localization and globalization. I'm having some difficulty understanding how to get the Date() function in javascript to work properly given the user's environment. My user base is split between Mexico (spanish) and the US (english). Since the Mexico date format is dd/mm/yyyy and the english format is mm/dd/yyyy, the standard Date(strDate) javascript constructor does not work for me.

Does anyone know the best way to handle globalization/localization of a javascript Date value? I have some business rules to enforce like dateA must be 90 days prior to dateB and dateB cannot exceed today.

+1  A: 

Matt Kruse developed a really interesting date library which should help with your particular case.

Here's a snippet of the method you should use for the issue you mentioned:

// ------------------------------------------------------------------
// parseDate( date_string [, prefer_euro_format] )
//
// This function takes a date string and tries to match it to a
// number of possible date formats to get the value. It will try to
// match against the following international formats, in this order:
// y-M-d   MMM d, y   MMM d,y   y-MMM-d   d-MMM-y  MMM d
// M/d/y   M-d-y      M.d.y     MMM-d     M/d      M-d
// d/M/y   d-M-y      d.M.y     d-MMM     d/M      d-M
// A second argument may be passed to instruct the method to search
// for formats like d/M/y (european format) before M/d/y (American).
// Returns a Date object or null if no patterns match.
// ------------------------------------------------------------------

function parseDate(val) {
    var preferEuro=(arguments.length==2)?arguments[1]:false;
    generalFormats=new Array('y-M-d','MMM d, y','MMM d,y','y-MMM-d','d-MMM-y','MMM d');
    monthFirst=new Array('M/d/y','M-d-y','M.d.y','MMM-d','M/d','M-d');
    dateFirst =new Array('d/M/y','d-M-y','d.M.y','d-MMM','d/M','d-M');
    var checkList=new Array('generalFormats',preferEuro?'dateFirst':'monthFirst',preferEuro?'monthFirst':'dateFirst');
    var d=null;
    for (var i=0; i<checkList.length; i++) {
     var l=window[checkList[i]];
     for (var j=0; j<l.length; j++) {
      d=getDateFromFormat(val,l[j]);
      if (d!=0) { return new Date(d); }
      }
     }
    return null;
    }
Luca Matteis
I did look at this, but in the end it ended up being a little bit more work to get it all put together. Thanks for your help though.
RSolberg
+6  A: 

Take a look at datejs, it handles localization very nicely. It comes with a lot of globalization setups. You just load the globalization setup of your current CultureInfo and datejs takes care of the rest.

Mauricio Scheffer
A: 

You could use: var a = Date.parseLocale(value, formats);

If you provide no custom formats, this function uses the Sys.CultureInfo.CurrentCulture property to determine the culture value.

You can take a look on: http://msdn.microsoft.com/en-us/library/bb397521.aspx

costin