我在脚本中使用了以下内容:
var startDate = new Date("10/12/2012");
var endDate = new Date("10/18/2012");我希望这些日期是动态创建与startDate作为上周一和endDate作为上周日。我尝试过以下几种方法:
var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
var last = first + 6; // last day is the first day + 6
var startDate = new Date(curr.setDate(first)).format("m/dd/yyyy");
var endDate = new Date(curr.setDate(last)).format("m/dd/yyyy");但由于某些原因,这并不起作用-- startDate或endDate变量没有输出任何内容。
你知道我做错了什么吗?
发布于 2012-11-21 20:52:21
Javascript datetime对象没有format方法。您需要使用库或自己生成字符串:
var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
var last = first + 6; // last day is the first day + 6
var startDate = new Date(curr.setDate(first));
startDate = "" + (startDate.getMonth() + 1) + "/" + startDate.getDate() + "/" + startDate.getFullYear();
var endDate = new Date(curr.setDate(last));
endDate = "" + (endDate.getMonth() + 1) + "/" + endDate.getDate() + "/" + endDate.getFullYear();这是一个fiddle http://jsfiddle.net/DPQeB/2/及其输出
2012年11月18日
11/24/2012
jQuery UI是一个允许您格式化日期的库。
发布于 2012-11-21 21:14:44
上周日使用获取
Date.today().moveToDayOfWeek(0, -1); // -1 indicates to go back最好使用库来操作日期。它会让你的生活变得轻松许多。
话虽如此,但我有一个长期目标,那就是理解JavaScript中的日期。它会帮助你做一些像调试这样的事情。
发布于 2016-06-07 19:05:47
如果从周日开始:
var today = new Date();
var sundayOfWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() - today.getDay()-8);
var mondayOfWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() - today.getDay()+1);
console.log( mondayOfWeek );
console.log( sundayOfWeek );https://stackoverflow.com/questions/13493569
复制相似问题