views:

600

answers:

3

Is there anyway we can know using JavaScript the Short Date Format used in the Control Panel -> Regional and Language Settings?

I know the using the combination of following we can get the Locale Long Name format

toString()
toLocaleString()
toLocaleDateString()
toLocaleTimeString()

But there is no direct function in JavaScript like toLocaleShortDateString().

Are there any scripts available to find out what the user setting is?

Thanks.

A: 

I don't know of a way to do that (you can get the language and try to deduct the locale from that).

I tried to cook a little something to try and do that (only tested on Firefox with one locale). should work as long as the short date string includes the date as digits, so it might fail for, say, arabic. It might have other bugs too, i don't know all the different locales peculiarities, this is just a concept...

function getShortDateFormat() {
    var d = new Date(1992, 0, 7);
    var s = d.toLocaleDateString();

    function formatReplacer(str) {
        var num = parseInt(str);
        switch (num % 100) {
            case 92:
                return str.replace(/.{1}/g, "Y");
            case 1:
                return str.length == 1 ? "mM" : "MM"
            case 7:
                return str.length == 1 ? "dD" : "DD"
        }
    }

    shortDateFormat = s.replace(/\d+/g, formatReplacer);
    return shortDateFormat;
}

getShortDateFormat();

The outputted format will be:

  • Y: the number of digits to represent years
  • dD = short day (i.e. use only one digit when possible)
  • DD = long day format (i.e. two digits always)
  • mM/MM - same for months

So in my browser, the shortDateformat you get is "MM/DD/YYYY".

Amitay Dobo
I get: "martes, DD de enero de YYYY"
Álvaro G. Vicario
Then obviously i need some more work on it :) (tested only on Firefox 3.5/Linux)
Amitay Dobo
+1  A: 

Try this, it works nicely for me. Has fallback for US short date format in case it can't be determined from the browser.

var getShortDateFormat = (function(){ 

  // default short date pattern
  var pattern = 'M/d/yyyy'; 

  // try to get the preferred short date pattern from the browser
  try {
    pattern = Sys.CultureInfo.CurrentCulture.dateTimeFormat.ShortDatePattern;
  } catch (e) { }

  // main getShortDateFormat function
  return function (date) {
    var m, d, y;
    return pattern.replace('yyyy', y=''+date.getFullYear())
      .replace('yy', y.substring(2))
      .replace('MM', zeroPad(m=date.getMonth()))
      .replace('M', m)
      .replace('dd', zeroPad(d=date.getDate()))
      .replace('d', d);
  }

  // zero-pad up to 2 digits 
  function zeroPad (n) { return (+n < 10 ? '0' : '') + n }

})();

The interesting bit is Sys.CultureInfo.CurrentCulture.dateTimeFormat.ShortDatePattern.

no