当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Incorrect day of week showing in input date field

问题描述:

I have some code on a website which isn't playing by 'my' rules.

The code:

<script>

function do_date()

{

v=document.getElementById('date').value;

n=v.split('-');

y=n[0];

m=n[1];

d=n[2];

var g=new Date(d,m,y);

var weekday=new Array(7);

weekday[0]="Sunday";

weekday[1]="Monday";

weekday[2]="Tuesday";

weekday[3]="Wednesday";

weekday[4]="Thursday";

weekday[5]="Friday";

weekday[6]="Saturday";

booking_date=d+'/'+m+'/'+y;

bd=y+''+m+''+d;

wd=weekday[g.getDay()]

document.getElementById('viewdate').innerHTML=wd+' '+booking_date;

}

</script>

<input type="date" id="date" name="date" value="" onchange="do_date()" style="width:150px;" />

the variable wd returns 5 for Friday 5th July 2013, but on Monday the 8th July 2013 it returns 2 in fact consecutive days from the 1st July to the 31st of July 2013 return the following:

g.getDay() log=0,1,2,4,5,6,0,2,3,5,0,1,2,3,5,6,0,1,3,4,5,0,2,3,4,6,0,1,2

which displays the days in a very strange order

Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday,Monday,Tuesday etc.

I have obviously done something wrong, but for the life of me I can not work it out.

If anyone could point me in the right direction, I would appreciate it :)

网友答案:

You are creating wrong the date variable. Look the syntax of the constructor (from doc):

new Date();
new Date(value);
new Date(dateString);
new Date(year, month, day [hour, minute, second, millisecond]);

Notice that the month has to be a value between 0 and 11. So in your code:

var g=new Date(y, m - 1, d);
分享给朋友:
您可能感兴趣的文章:
随机阅读: