本文介绍了当日期在不同月份时,如何获取当前一周的第一天和最后一天?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,对于2016年3月27日至2016年2月4日,日期位于不同的月份.
For example, in the case of 03/27/2016 to 04/02/2016, the dates fall in different months.
var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay();
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();
推荐答案
getDay 方法返回星期几,星期天为0,星期六为6.因此,如果您的星期是从星期天开始,只需从当前日期中减去以天为单位的当前天数即可开始,并加上6天即可获得结束,例如
The getDay method returns the number of the day in the week, with Sunday as 0 and Saturday as 6. So if your week starts on Sunday, just subtract the current day number in days from the current date to get the start, and add 6 days get the end, e.g.
function getStartOfWeek(date) {
// Copy date if provided, or use current date if not
date = date? new Date(+date) : new Date();
date.setHours(0,0,0,0);
// Set date to previous Sunday
date.setDate(date.getDate() - date.getDay());
return date;
}
function getEndOfWeek(date) {
date = getStartOfWeek(date);
date.setDate(date.getDate() + 6);
return date;
}
document.write(getStartOfWeek());
document.write('<br>' + getEndOfWeek())
document.write('<br>' + getStartOfWeek(new Date(2016,2,27)))
document.write('<br>' + getEndOfWeek(new Date(2016,2,27)))
这篇关于当日期在不同月份时,如何获取当前一周的第一天和最后一天?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!