Вопрос

I want to set Jquery UI DatePicker date format from browser language, for example if "English (United Kingdom)" in Google Chrome is on top in Language and input settings... (chrome://settings/languages) then date format would be dd/mm/yyyy and if "English (United States)" is on the top of the list then date format should be mm/dd/yyyy. Is there any way to set Date Format from Browser Language in Chrome, Firefox and IE...?

Это было полезно?

Решение

In your case I would suggest to check the language like

var userLang = navigator.language || navigator.userLanguage; 
// detect browser language but not a decent one 
if (userLang === "en-US") {
  $( ".selector" ).datepicker( "option", "dateFormat", "mm/dd/yyyy" );
} else {
  $( ".selector" ).datepicker( "option", "dateFormat", "dd/mm/yyyy" );
}

Update:

I was looking into localization of jQuery datepicker, and here is a nice discussion and a nice plugin for it.

jQuery-localization, which detects the language and loads the respective regional language for it

$.localise('js/jquery.ui.datepicker');

Note: By default, it looks at the locale set for the browser and requests localisations of the specified package based on that. For example, if the locale is Portuguese/Brazil (pt-BR), it will load js/jquery.ui.datepicker-pt.js and js/jquery.ui.datepicker-pt-BR.js.

Другие советы

This is how it's done in the current project I'm working on. Not sure if it's the best approach as I believe there are language files available in jQuery UI, however ...

var cfg = {
    container: '.datepicker',
    regional: {
        nl: {
            closeText: 'Sluiten',
            prevText: '←',
            nextText: '→',
            currentText: 'Vandaag',
            monthNames: ['januari', 'februari', 'maart', 'april', 'mei', 'juni', 'juli', 'augustus', 'september', 'oktober', 'november', 'december'],
            monthNamesShort: ['jan', 'feb', 'maa', 'apr', 'mei', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec'],
            dayNames: ['zondag', 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag'],
            dayNamesShort: ['zon', 'maa', 'din', 'woe', 'don', 'vri', 'zat'],
            dayNamesMin: ['zo', 'ma', 'di', 'wo', 'do', 'vr', 'za'],
            weekHeader: 'Wk',
            dateFormat: 'dd-mm-yy',
            firstDay: 1,
            isRTL: false,
            showMonthAfterYear: false,
            yearSuffix: ''
        }
    }
};

// extracted activation function
$.datepicker.regional = $.extend({}, $.datepicker.regional, cfg.regional);
$.datepicker.setDefaults($.datepicker.regional.nl);
this.datepicker.datepicker();

So you can add languages in the cfg object and choose a custom format. Only thing left to do is make the language, passed to datepicker(), dynamic. Perhaps from the URL, cookie, session, server variable, ... depending on how your project uses languages.

Hope it helps.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top