172

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

4

7 回答 7

396

使用.getDate而不是.getDay.

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

于 2012-11-13T10:44:54.690 回答
19

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

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

于 2012-11-13T10:45:11.693 回答
15

getDay()会给你星期几。您正在寻找getDate().

于 2012-11-13T10:45:46.900 回答
6

我有一个类似的问题。date.getMonth()返回范围为 的索引0 to 11。一月是0。如果您创建一个新date()的 -object 并且想要获取有关 costum 日期而不是当前日期的信息,则您只需将月份减少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()];
}
于 2016-04-11T12:14:39.183 回答
3

从现在开始,您可能希望对 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));

于 2020-06-09T00:31:35.293 回答
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);
 });
于 2016-08-26T12:42:57.973 回答
0

当你使用.getDay()函数时,这个考虑月份的数字从0开始而不是从1开始,那么如果你使用日期new Date(2021-11-04),.getDay()函数将考虑日期12 月 4 日而不是 11 月...

然后,要获得 11 月的第 4 天,您需要将“2021-10-04”传递给 Date() 类。

于 2021-11-05T02:31:20.167 回答