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

北城以北 提交于 2019-12-12 01:39:44

问题


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


回答1:


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);


来源:https://stackoverflow.com/questions/11469917/javascripts-dateobject-jump-from-may-31st-to-next-month-gets-july-1st

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!