2016-03-29 40 views
0

例如,在2016年3月27日至2016年4月2日的情况下,日期会在不同的月份中出现。如何获得本周的第一天和最后一天,当天有几天不同?

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(); 

回答

0

getDay方法返回在本周日的数,星期日为0,星期六为6.所以如果你的星期从星期天开始,只需从当前日期中减去当天的天数就可以开始,并添加6天ays即将结束,例如

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)))

0

我喜欢moment library对于这种事情:

moment().startOf("week").toDate(); 
moment().endOf("week").toDate(); 
+0

有没有办法做到这一点在JavaScript中没有的时刻。 – anna

+0

我认为你将不得不做一些像Zarana推荐的东西,将日期转换为整数值并将其作为数字处理。 – Shaun

+0

答案应该包括一个解释,并且不应该要求在问题中没有提及或标记的库。 – RobG

0

你可以试试这个:

var currDate = new Date(); 
day = currDate.getDay(); 
first_day = new Date(currDate.getTime() - 60*60*24* day*1000); 
last_day = new Date(currDate.getTime() + 60 * 60 *24 * 6 * 1000); 
+0

要获得一周中最后一天的价值,您必须从最大星期几减去日价值:'last_day = new Date(currDate.getTime()+ 60 * 60 * 24 *(6 - day) * 1000);' – Shaun

相关问题