0

I am selecing a date from jquery datepicker and I want to pick the starting and ending date of the week that precedes this date. - for example picking April 10, 2013 should return March 31, 2013 and April 6, 2013. Sunday is the first day of the week and Saturday is last.

Below is my code.

$weekday = $d->format('w');
$diff = 7 + ($weekday == 0 ? 6 : $weekday - 0); //to make week start from monday till     sunday add 1 to weekday -

$start1 = $d->modify("-$diff day");
$start_date = $d->format('Y-m-d');  

$end1 =  $d->modify('+6 day');
$stop_date = $d->format('Y-m-d');

The code works fine, at least mostly. However, when I pick any sunday I get a wrong a non expected result which is the previous week of the previous week. for example, if I select March 31, 2013 - I should get march 24 and march 30,, but I am getting march 28 and march 24.

Where am I going wrong ?

tony9099
  • 4,567
  • 9
  • 44
  • 73

1 Answers1

0

Try this, it should solve your problem:

$input = 'April 10, 2013'; // come from jquery

$dt = new DateTime($input . ' -1week');

$monday = clone $dt->modify(('Sunday' == $dt->format('l')) ? 'Monday last week' : 'Monday this week');
$sunday = clone $dt->modify('Sunday this week');

printf("You've selected a date in the week from %s to %s\n",
    $monday->format('Y-m-d'),
    $sunday->format('Y-m-d')
);
hek2mgl
  • 152,036
  • 28
  • 249
  • 266