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

2020/11/11 23:22 · javascript ·  · 0评论

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

使用.getDate代替.getDay

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

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

https://developer.mozilla.org/zh-CN/docs/JavaScript/Reference/Global_Objects/Date/getDay

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

我有一个类似的问题。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()];
}
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);
 });

从现在开始,您可能想对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));
本文地址:http://javascript.askforanswer.com/date-getdayjavascriptfanhuicuowuderiqi.html
文章标签: ,  
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!