Date.getDay()javascript返回错误的一天

Date.getDay() javascript returns wrong day

嗨,我是javascript的新手
我有这样的javascript代码

1
2
3
4
5
6
7
8
9
10
11
12
alert(DATE.value);
var d = new Date(DATE.value);
var year = d.getFullYear();
var month = d.getMonth();
var day = d.getDay();
alert(month);
alert(day);
if(2012 < year < 1971 | 1 > month+1 > 12 | 0 >day > 31){
    alert(errorDate);
    DATE.focus();
    return false;
}

例如:DATE.value ="11/11/1991"

当我打电话给alert(day);时,它显示我3;
当我打电话给alert(d);时,它会返回正确的信息。


使用.getDate而不是.getDay

The value returned by getDay is an integer corresponding to the day of the week: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on.


来自MDN关于getDay:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getDay

Returns the day of the week for the specified date according to local
time.

你可能想要getDate:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getDate

Returns the day of the month for the specified date according to local
time.


getDay()返回星期几。 但是,您可以使用getDate()方法。

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getDay


getDay()会为您提供一周中的某一天。 您正在寻找getDate()


我遇到了类似的问题。 date.getMonth()返回范围为0 to 11的索引。 一月是0。 如果您创建一个新的date()对象,并且您希望获得有关costum日期而不是当前日期的信息,则必须仅将月份减少1

像这样:

1
2
3
4
5
6
7
8
9
10
11
function getDayName () {
var year = 2016;
var month = 4;
var day = 11;

var date = new Date(year, month-1, day);
var weekday = new Array("sunday","monday","tuesday","wednesday",
                   "thursday","friday","saturday");

return weekday[date.getDay()];
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function formatDate(date, callback)
{
var weekday = new Array("Sunday","Monday","Tuesday","Wednesday",    "Thursday","Friday","Saturday");
var day = weekday[date.getDay()];
console.log('day',day);
var d = date.getDate();
var hours = date.getHours();
ampmSwitch = (hours > 12) ?"PM" :"AM";
if (hours > 12) {
    hours -= 12;

}
else if (hours === 0) {
    hours = 12;
}
var m = date.getMinutes();
var months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
var month = months[date.getMonth()];
var year = date.getFullYear();
newdate = day + ', ' + month + ' ' + d + ',' + year + ' at ' + hours +":" + m +"" + ampmSwitch
callback(newdate)
}

并使用此代码调用

1
2
3
4
date="Fri Aug 26 2016 18:06:01 GMT+0530 (India Standard Time)"
formatDate(date,function(result){
   console.log('Date=',result);
 });