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

时间:2012-11-13 10:42:46

标签: javascript date

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

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);时,它会返回正确的信息。

6 个答案:

答案 0 :(得分:251)

使用.getDate代替.getDay

  

getDay返回的值是一个对应于星期几的整数:0表示星期日,1表示星期一,2表示星期二,依此类推。

答案 1 :(得分:13)

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

  

根据本地返回指定日期的星期几   时间。

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

  

根据本地返回指定日期的月中某天   时间。

答案 2 :(得分:11)

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

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

答案 3 :(得分:8)

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

答案 4 :(得分:1)

从现在开始,您可能想对Date对象使用以下功能:

    function dayOf(date)
    {
        return date.getDate();
    }

    function monthOf(date)
    {
        return date.getMonth() + 1;
    }

    function yearOf(date)
    {
        return date.getYear() + 1900;
    }

    function weekDayOf(date)
    {
        return date.getDay() + 1;
    }
    
    var date = new Date("5/15/2020");
    console.log("Day: " + dayOf(date));
    console.log("Month: " + monthOf(date));
    console.log("Year: " + yearOf(date));

答案 5 :(得分:0)

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

并使用此代码调用

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