-1

We have requirement that we need to pass the current date and get the start date of the week. While doing this the start day is user defined like if the user defines the start day as 0 ,day of the week will be sunday,if 1 then start day will be monday and like wise.. We tried the solution from the link Start day of the Week

But it only handles monday or sunday.

I tried the following code but it will fail select friday or saturday ,it will break

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

Let me know if any one has idea to do this.

Thanks.

Vaibhav
  • 579
  • 4
  • 18

3 Answers3

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/>");
jmgross
  • 2,306
  • 1
  • 20
  • 24
-1

This is my "home-made" solution :

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

I work with Date objects but of course you can get the day you were looking for with date.getDay()

Hope it helps

bviale
  • 5,245
  • 3
  • 28
  • 48
-1

I have tried in Jquery and found the solution. Below is the code. It works good.

 $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 ;
Ramya
  • 1
  • 1