Search code examples
javascriptdatepicker

datepicker date off by one day


The date returned by date picker is off by one day. Is it a problem in my code or is it a bug?

The date sent to date_picker is 2012-03-21. The date returned by datepicker is Tue Mar 20 2012.

    var end_date = end_calendar.getFormatedDate("%Y-%m-%d");
    end_date = $.datepicker.formatDate('D M dd yy', new Date(end_date));

I've struggled with this issue also and discovered a salient point on the issue so I thought I'd add a code snippet that displays the problem.

The following code only:

  1. sets the valueAsDate property
  2. reads the valueAsDate property

But on my systems it always shows wrong date when I read the property.

function initDate(){
document.querySelector("#mainDate").valueAsDate = new Date();
}
function showDate(){
    alert(document.querySelector("#mainDate").valueAsDate);
  }
<body onload="initDate()">
    <h2>Reading the property we set gets different value</h2>
    <p> Notice that the code only:
    <ul><li>sets the value using valueAsDate property</li>
    <li>reads the same property valueAsDate </li>
    </ul>
    <input type="date" id="mainDate">
    <button onclick="showDate()">show date</button>
  </body>

Here's a snapshot of the value I get that shows that I always get a date that is one day less than the value that the control displays. Value is one day less than displayed in control


Solution

  • Seems to be a bug. If the string sent to Date() is formatted as 2012/03/21 instead of 2012-03-21. The date seems right.