Date.getDay()JavaScript返回错误的日期


146

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


Answers:


329

使用.getDate代替.getDay

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


154
真的很傻,这个函数的设计者没有将它称为getDayOf Week。不,那太明显了。
AndroidDev 2014年

41
@AndroidDev我同意!而且,.getDate期望一个人能得到完整的日期,而不仅仅是一天。

47
还有更多信息:函数getMonth返回一个从0到11的整数,其中1表示0,12表示11。他们一定在那边抽烟
taralex

13
这里还有更多:getYear()实际上是年份减去1900!
Guilhem Fry

完全不一致的设计〜Date.getYear() okay, Date.getMonth() okay, Date.getDate() what?
埃迪乙



5

我有一个类似的问题。date.getMonth()返回范围为的索引0 to 11。一月是0。如果您创建一个新对象,date()并且想要获得有关某服装日期而非当前日期的信息,则只需将月份减少1

像这样

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()];
}

很棒的Sven ...这是我的解决方案,可以减负一个...谢谢。
juanram0n

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

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.