如何获得当周的星期一?

时间:2017-02-10 23:23:48

标签: javascript html css

(function () {
    var date = new Date().toISOString().substring(0, 10),
        field = document.querySelector('#date');
    var day = new Date(date);
    var getMonday = day.getDay(),
        diff = date.getDate() - getMonday + (getMonday == 0 ? -6:1);
    field.value = new Date(date.setDate(diff));
    console.log(date);
})();

我想要获得当前日期的星期一。

我一直在收到错误,不知道如何解决它

TypeError: date.getDate is not a function
    at index.html:394
    at index.html:398
(anonymous) @ index.html:394
(anonymous) @ index.html:398

所谓复制的帖子只询问如何获取日期。我的问题有类似的代码,但我收到的错误消息从未在问题中解决

1 个答案:

答案 0 :(得分:2)

您将第一行中的日期转换为字符串: date = new Date().toISOString().substring(0, 10)导致错误的原因...日期不再是Date对象。

---编辑:解决方案 我建议你为以后的任何一个用作ISO字符串声明一个额外的变量,或者仅在输出时进行转换: 为此,我建议将您的格式添加到Date对象的原型

Date.prototype.myFormat = function() { 
    return this.toISOString().substring(0, 10); 
}

更新您的初始代码:

var date = new Date(), 
str_date=date.toISOString().substring(0, 10),
field = document.querySelector('#date'), 
day = new Date(date),
getMonday = day.getDay(),
diff = date.getDate() - getMonday + (getMonday == 0 ? -6:1);

console.log(date);
console.log(str_date);
console.log(new Date(date.setDate(diff)));
console.log(new Date(date.setDate(diff)).myFormat());

//Now you can update your field as needed with date or string value
field.value = new Date(date.setDate(diff));
field.value = new Date(date.setDate(diff)).myFormat();

如果你需要更多的地方,那么getMonday也是一个功能......

快乐的编码, Codrut