Search code examples
javascriptwebpackmomentjsdatetimepickereonasdan-datetimepicker

Set valid locale for datetimepicker


I have quite strange issue. I'm using jQuery 3, Boostrap 3 and this DateTimepicker. The problem is that in datetime picker at first attempt I'm always getting invalid locale (always English), but on second attempt (and further) it's valid. The end of my website look like this:

 <script>
    $.when($.ready).then(function () {
        moment().locale('da');

        $('.datetimepicker').datetimepicker({
            locale: 'da',
            viewMode: 'years',
            format: 'YYYY-MM-DD',
            defaultDate: false,
            useCurrent: false,
            viewDate: '1999-04-20'
        });
    })
</script>
</body>
</html>

I've added this moment().locale('da'); because I thought it would solve the issue but it doesn't in my case.

Any clue how can I force this to make it work?

If it's important, I'm using WebPack and my JS file looks like this:

window.$ = window.jQuery = require('jquery');

require('bootstrap-sass');
require('bootstrap-select');
require('eonasdan-bootstrap-datetimepicker');

var moment = require('moment');
window.moment = moment;

It seems that when I change in this file:

var moment = require('moment');
window.moment = moment;

to

var moment = require('moment');
moment.locale('da');
window.moment = moment;

Locale is set in valid way at 1st attempt. Unfortunately I have multiple languages and probably it doesn't make much sense to have multiple JS files just to make moment use valid locale.

Is there any way to solve this?


Solution

  • It seems it was easy. I've used:

    moment().locale('da');
    

    what was causing no errors in JS console, but to make it work it has to be

    moment.locale('da');