我们要求我们需要传递当前日期并获取一周的开始日期。在这样做时,开始日是用户定义的,如果用户将开始日定义为0,星期几将是星期日,如果1则开始日将是星期一,并且明智... 我们尝试了链接Start day of the Week
中的解决方案但它只处理星期一或星期日。
我尝试了以下代码,但是选择星期五或星期六会失败,它会破坏
var startDate = 5;
if (!d) return;
d = new Date(d);
var day = d.getDay(),
diff = d.getDate() - day;
var sunday = new Date(d.setDate(diff));
//add days to sunday to adjust sunday,monday,tue,wed...
return new Date(sunday.getYear(), sunday.getMonth(),sunday.getDate()-(7-startDate));
让我知道是否有人有想法这样做。
感谢。
答案 0 :(得分:3)
function getStartOfWeek(index) {
var d = new Date();
var day = d.getDay();
var diff = index - day;
if(index > day) {
diff -= 7;
}
return new Date(d.setDate(d.getDate() + diff));
}
document.write(getStartOfWeek(0).toLocaleDateString()+"<br/>");
document.write(getStartOfWeek(1).toLocaleDateString()+"<br/>");
document.write(getStartOfWeek(2).toLocaleDateString()+"<br/>");
document.write(getStartOfWeek(3).toLocaleDateString()+"<br/>");
document.write(getStartOfWeek(4).toLocaleDateString()+"<br/>");
document.write(getStartOfWeek(5).toLocaleDateString()+"<br/>");
document.write(getStartOfWeek(6).toLocaleDateString()+"<br/>");
&#13;
答案 1 :(得分:-1)
这是我的“自制”解决方案:
getWeekStartDate = function(date)
{
var d = new Date(date);
// Sunday
if (date.getDay() === 0)
return new Date(d.setDate(date.getDate()-6));
// Monday
if (date.getDay() === 1)
return date;
return new Date(d.setDate(date.getDate() - (date.getDay() - 1)));
};
我使用Date对象,但当然你可以通过date.getDay()
希望有所帮助
答案 2 :(得分:-1)
我在Jquery尝试过并找到了解决方案。下面是代码。它运作良好。
$first_day_of_the_week = 'Monday';
$start_of_the_week = date('Y-m-d',strtotime("Last $first_day_of_the_week"));
if ( strtolower(date('l')) === strtolower($first_day_of_the_week) )
{
$start_of_the_week = date('Y-m-d',strtotime('today'));
}
echo $start_of_the_week ;