javascriptdatepikaday

Pikaday date formatting without Moment.js


I'm using Pikaday, which requires Moment.js to format dates. This allows easy date formatting:

var picker = new Pikaday({
  format: 'YYYY-MM-DD'
});

However, when I include the Pikaday npm package, Moment.js is over 40kb. Literally all I need it for is to change the date format to YYYY-MM-DD from the practically unusable default Pikaday format.

Can I do this without having to include a 40kb library?


Solution

  • If you want to use only format YYYY-MM-DD, you can build the date string using native Date methods:

    const picker = new Pikaday({
      field: document.getElementById('datepicker')
     ,onSelect: date => {
        const year = date.getFullYear()
             ,month = date.getMonth() + 1
             ,day = date.getDate()
             ,formattedDate = [
                year
               ,month < 10 ? '0' + month : month
               ,day < 10 ? '0' + day : day
              ].join('-')
        document.getElementById('datepicker').value = formattedDate
      }
    })
    

    Demo

    const picker = new Pikaday({
      field: document.getElementById('datepicker')
     ,onSelect: date => {
        const year = date.getFullYear()
             ,month = date.getMonth() + 1
             ,day = date.getDate()
             ,formattedDate = [
                year
               ,month < 10 ? '0' + month : month
               ,day < 10 ? '0' + day : day
              ].join('-')
        document.getElementById('datepicker').value = formattedDate
      }
    })
    @import url("https://rawgit.com/dbushell/Pikaday/master/css/pikaday.css");
    <script src="https://rawgit.com/dbushell/Pikaday/master/pikaday.js"></script>
    <input type="text" id="datepicker">