Search code examples
knockout.jsmomentjsdaterangepicker

Knockout Daterangepicker correct moment formatting of date


I'm trying to use datepicker: https://sensortower.github.io/daterangepicker to have a datepicker with knockout.

All ok, but I also want the custom date fields in the picker itself to be "DD-MM-YYY" (and not as currently "DD/MM/YYYY"

My template definition is:

<input type="text" readonly class="form-control" 
  data-bind=" daterangepicker: dateRange,
              daterangepickerOptions: { 
                maxDate: [moment().add(20,'years')],                                  
                ranges: {
                  'Komende maand': [moment(), moment().add(1,'month')],
                  'Komende week': [moment(), moment().add(1,'week')],
                  'Altijd': 'all-time',
                  'Aangepast:': 'custom'
                },
                periods: ['day'],
                locale: 'nl',
                timeZone: null
              },
              daterangepickerFormat: 'DD-MM-YYYY'," />

So in the picker itself it display the current dates to change, but these are still in "en" format.

enter image description here


Solution

  • Are you sure the nl locale setting flag is supported? Replace this by:

    locale: { inputFormat: 'DD-MM-YYYY' },
    

    and the label changes.

    Explanation:

    I tried to find out which of the library's source code rendered the label you want to change. Turns out there's a setting being used called inputFormat, which should be stored in a locale object.

    Here's how default settings get applied to this object:

    Config.prototype._locale = function(val) {
      return $.extend({
        applyButtonTitle: 'Apply',
        cancelButtonTitle: 'Cancel',
        inputFormat: 'L',
        startLabel: 'Sart',
        endLabel: 'End'
      }, val || {});
    };
    

    You see the "L" value being used as default format, which results in a DD/MM/YYYY string. Extending an object with a string ("nl" in your template) doesn't make much sense to me, so my guess is that you'll have to create your own settings object. You could compute it from moment.js' locale settings.

    (A codepen in which I threw together a file that has all the libraries you're using and shows that my proposal works: http://codepen.io/anon/pen/xEWJKd)