2017-02-10 147 views
0
(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 

只要求对如何获得的日期。我的问题有类似的代码,但我得到的错误信息是从来没有解决的问题

+2

的可能的复制[JavaScript的 - 获得一周的从当前日期的第一天(http://stackoverflow.com/questions/4156434/javascript-获取本周的第一天至今日期) – GillesC

+0

@GillesC我在帖子中有新信息未被问题回答 –

+0

您正在尝试获取** getDate()**从字符串 - 它没有这样的方法,而是使用** date **类型 – Alexey

回答

2

您将日期转换为字符串在第一行: date = new Date().toISOString().substring(0, 10)这是什么导致错误...日期不再是日期目的。

---编辑:解决方案 我建议你要么声明一个额外的变量任何你作为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

相关问题