0

I'm currently using jquery ui slider plugin to set a range between two dates. I need the date output to be YYYY-MM-DD instead of fully written out like Mon Nov 29, 2021.

I'm using this function I found on codepen to convert the default jquery range slider into a date range slider between two dates. Right now the output of the dates is written out fully like I showed above. I need it to be in the format of YYYY-MM-DD. I tried changing min, max and the values options to new Date().toISOString().slice(0, 10), but it gave me an invalid date error. If anyone knows how to change the date format to be YYYY-MM-DD, it would be greatly appreciated!

  $(function() {
    $( "#slider-range" ).slider({
      range: true,
      min: new Date('2010.01.01').getTime() / 1000,
      max: new Date('2014.01.01').getTime() / 1000,
      step: 86400,
      values: [ new Date('2013.01.01').getTime() / 1000, new Date('2013.02.01').getTime() / 1000 ],
      slide: function( event, ui ) {
        $( "#amount" ).val( (new Date(ui.values[ 0 ] *1000).toDateString() ) + " - " + (new Date(ui.values[ 1 ] *1000)).toDateString() );
      }
    });
    $( "#amount" ).val( (new Date($( "#slider-range" ).slider( "values", 0 )*1000).toDateString()) +
      " - " + (new Date($( "#slider-range" ).slider( "values", 1 )*1000)).toDateString());
  });

Heres a link to the codepen I'm going off of. https://codepen.io/2rod/pen/JtIki

Matthew
  • 253
  • 1
  • 15
  • 1
    `toISOString().slice(0, 10)` seem to work fine in your codepen. But do be aware that toISOString will be using UTC dates. Also worth noting `'2010.01.01'` is not a valid date for the date constructor, it might work, or it might not it's down to the browsers implementation. `'2010-01-01'` is valid, but again remember this is UTC if that matters. – Keith Nov 29 '21 at 13:42
  • See [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) and [*How to format a JavaScript date*](https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date). – RobG Nov 29 '21 at 20:16

0 Answers0