我有today = new Date();
对象.我需要获得本周的第一天和最后一天.星期日和星期一我需要两种变体作为一周的开始和结束日.我现在对代码有点困惑.你可以帮帮我吗?
Ray*_*nos 168
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 firstday = new Date(curr.setDate(first)).toUTCString();
var lastday = new Date(curr.setDate(last)).toUTCString();
firstday
"Sun, 06 Mar 2011 12:25:40 GMT"
lastday
"Sat, 12 Mar 2011 12:25:40 GMT"
Run Code Online (Sandbox Code Playgroud)
这适用于本周的第一天=星期日和本周的最后一天=星期六.将其延长至周一至周日运行是微不足道的.
使其在不同月份的第一天和最后一天工作留给用户锻炼
Bru*_*mos 48
小心接受的答案,它没有将时间设置为00:00:00和23:59:59,因此您可能会遇到问题.
我建议使用Moment.js来处理日期.对于你的情况:
var startOfWeek = moment().startOf('week').toDate();
var endOfWeek = moment().endOf('week').toDate();
Run Code Online (Sandbox Code Playgroud)
这只是一个小用例,执行大量复杂操作非常简单.
您可以在此处了解更多信息:http://momentjs.com/
小智 38
您还可以使用以下代码行来获取一周的第一个和最后一个日期:
var curr = new Date;
var firstday = new Date(curr.setDate(curr.getDate() - curr.getDay()));
var lastday = new Date(curr.setDate(curr.getDate() - curr.getDay()+6));
Run Code Online (Sandbox Code Playgroud)
希望它会有用..
小智 15
这是开始第一天和最后一天的快速方式.知道:
1天= 86,400,000毫秒.
JS日期值以毫秒为单位
食谱:找出你需要删除多少天才能获得本周的开始日期(乘以1天的毫秒数).之后剩下的就是增加6天来结束你的结束日.
var startDay = 1; //0=sunday, 1=monday etc.
var d = now.getDay(); //get the current day
var weekStart = new Date(now.valueOf() - (d<=0 ? 7-startDay:d-startDay)*86400000); //rewind to start day
var weekEnd = new Date(weekStart.valueOf() + 6*86400000); //add 6 days to get last day
Run Code Online (Sandbox Code Playgroud)
SHI*_*IVA 13
对@Chris Lang 答案的小改动。如果您希望星期一作为第一天,请使用此选项。
Date.prototype.GetFirstDayOfWeek = function() {
return (new Date(this.setDate(this.getDate() - this.getDay()+ (this.getDay() == 0 ? -6:1) )));
}
Date.prototype.GetLastDayOfWeek = function() {
return (new Date(this.setDate(this.getDate() - this.getDay() +7)));
}
var today = new Date();
alert(today.GetFirstDayOfWeek());
alert(today.GetLastDayOfWeek());
Run Code Online (Sandbox Code Playgroud)
谢谢@Chris Lang
优秀(和不可变)的date-fns库最简洁地处理这个问题:
const start = startOfWeek(date);
const end = endOfWeek(date);
Run Code Online (Sandbox Code Playgroud)
小智 5
这适用于年和月的变化。
Date.prototype.GetFirstDayOfWeek = function() {
return (new Date(this.setDate(this.getDate() - this.getDay())));
}
Date.prototype.GetLastDayOfWeek = function() {
return (new Date(this.setDate(this.getDate() - this.getDay() +6)));
}
var today = new Date();
alert(today.GetFirstDayOfWeek());
alert(today.GetLastDayOfWeek());
Run Code Online (Sandbox Code Playgroud)