Search code examples
javascriptdatedatepickermonthcalendar

Javascripts dateObject: jump from May 31st to next month gets July 1st


I had to build a DatePicker without any Library (like jQuery) for a client. I succeeded on my local machine. However my client is using it now and it shows some odd behaviour if its included in his web-app.

If i select the 31st of May and scroll to the next month i end up at July 1st. The DateObject infact has May 31st before i click the button to fire up the "jumpToNextMonth" function. I assume the dateObject jumps to June 31st which is nonexistend and then goes one foward to 1st of july. This happens in August as well and all other 30-day-months which are followed by 31-day-months.

The line which is fired up on click is

this.currentDate = new Date(this.currentDate.getFullYear(),
                           this.currentDate.getMonth() + 1,
                           this.currentDate.getDate());

I don't see this behaviour on my local machine nor do i see it running an apache server. I can't imagine what corrupts the date object on my clients web-app and unfortunately i don't have access to their files.

I'd really appreciate if you'd help me answering these two questions:

  1. why is it not happening on my local machine
  2. how do i fix it without setting the Day to "1" e.g. this.currentDate = new Date(this.currentDate.getFullYear(), this.currentDate.getMonth() + 1, 1);

I found similar non-answered questions here Flex Mobile 4.6: DateSpinner dateAndTime jumping from Jan 31st to March 1st


Solution

  • You have answered your own question. June 31st in the object is effectively July 1st.

    Does this solve your issue?

    function daysInMonth(month, year)
    {
        return 32 - new Date(year, month, 32).getDate();
    }
    
    var y = this.currentDate.getFullYear();
    var m = this.currentDate.getMonth() + 1;
    var d = Math.min(this.currentDate.getDate(), daysInMonth(m, y);
    this.currentDate = new Date(y, m, d);