[英]How do I get the Monday of the current week?
(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);
})();
I am trying to get the Monday of the current date. 我正在尝试获取当前日期的星期一。
I keep getting errors about it and not sure how to resolve it 我不断收到有关它的错误,不确定如何解决
TypeError: date.getDate is not a function
at index.html:394
at index.html:398
(anonymous) @ index.html:394
(anonymous) @ index.html:398
Post of so called Duplicate only asks for the how to get the date. 所谓的Duplicate帖子仅询问如何获取日期。 My question has similar code but I am getting error messages that was never addressed in the question
我的问题有类似的代码,但我收到了问题中从未解决的错误消息
You transform the date to string in the first line: date = new Date().toISOString().substring(0, 10)
that is what causes the error... date is no longer a Date object. 您在第一行中将日期转换为字符串:
date = new Date().toISOString().substring(0, 10)
,这是导致错误的原因... date不再是Date对象。
--- EDIT: Solution I would suggest you to either declare an additional variable for any of your later use as ISO string, or to make the conversion after only when output: For this, I'd suggest add your format to the Date object's prototype ---编辑: 解决方案我建议您为以后用作ISO字符串的任何一个声明一个附加变量,或者仅在输出后进行转换:为此,建议您将格式添加到Date对象的原型
Date.prototype.myFormat = function() {
return this.toISOString().substring(0, 10);
}
Update your initial code like this: 像这样更新您的初始代码:
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();
If you need it in more places make the getMonday also a function... 如果需要更多地方,请将getMonday用作函数...
Happy coding, Codrut 快乐编码,Codrut
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.