Luke Luke - 8 months ago 39
jQuery Question

Construct a javascript date from a string without timezone (for JqueryUI datepicker)

I'm using the jQueryUI Datepicker library and I need to supply it with a date that is dynamically loaded for the min date.

I set up my datepicker:

$("#thePicker" ).datepicker({
dateFormat: 'yy-mm-dd',
showOtherMonths: true,
changeMonth: true,
changeYear: true,
minDate: new Date('2016-04-28'),

Where '2016-04-28' is a string that could vary when loaded.

This though sets the minimum allowable date to April 27, 2016, due to a timezone conversion.

How should I construct this new Date for the minDate when I have a string of the format shown above supplied so that no timezone is relevant?


If the date is a string and always "YYYY-MM-DD", I would do something like this:

$(function() {
  var dString = "2016-04-28";
  var yy = parseInt(dString.substring(0, 4));
  var mm = parseInt(dString.substring(5, 7)) - 1;
  var dd = parseInt(dString.substring(8));
    dateFormat: 'yy-mm-dd',
    showOtherMonths: true,
    changeMonth: true,
    changeYear: true,
    minDate: makeDate("2016-04-28"),
    /* Alternate Method 1
    minDate: new Date(yy, mm, dd),
    /* Alternate Method 2
    minDate: new Date(parseInt("2016-04-28".substring(0,4)), parseInt("2016-04-28".substring(5,7))-1, parseInt("2016-04-28".substring(8))),

  function makeDate(ds) {
    var yy = parseInt(ds.substring(0, 4));
    var mm = parseInt(ds.substring(5, 7)) - 1;
    var dd = parseInt(ds.substring(8));
    var d = new Date(yy, mm, dd);
    return d;

Depending on how often you will be using this in your page will define what method will work best for you.