Oct 092012
 

The Code

After messing with tons of examples of PHP on an the easiest way to get the start of week’s date, I ended up combining a few examples and adding a bit of my own code.

This Week Starting Monday Date

Get this Mondays timestamp function

function mondayTimestamp($year, $week) {
// According to ISO-8601, January 4th is always in week 1
$halfwayTheWeek = strtotime($year.”0104 +”.($week – 1).” weeks”);
// Subtract days to Monday
$dayOfTheWeek = date(“N”, $halfwayTheWeek);
$daysToSubtract = $dayOfTheWeek – 1;
// Calculate the week’s timestamp
$unixTimestamp = strtotime(“-$daysToSubtract day”, $halfwayTheWeek);
// return the timestamp for Monday
return $unixTimestamp;
}

We need to pass the year and number of the week to the function.

// get this year
$year = date(“Y”);
// get the number of the week in this year
$week = date(“W”);
// get Mondays Timestamp
$mondaysDate = mondayTimestamp($year, $week);
// format the Date of Monday Starting this Week
$its_monday = date(‘Y-m-d’,$mondaysDate);
// =========== OUTPUT ============
echo “Start of Week: ” . $its_monday;

Last Week Starting Monday

Use the function above to get Mondays timestamp, but pass it a value for last week (W – 1) instead of this week.

// get last weeks number, if week = 1 set last_week to 52 and subtract 1 from the year
if (date(“W”) == 1) {
$last_week = 52;
$year = $year – 1;
} else {
  $last_week = date(“W”)-1;
}
// format last monday timestamp
$lastMondaysDate = mondayTimestamp($year, $last_week);
// format the Date of Monday Starting Last Week
$last_week_monday = date(‘Y-m-d’,$lastMondaysDate);
// ============== OUTPUT ===================
echo “Start of Last Week: ” . $last_week_monday;

=====================================================================
=====================================================================

Sorry, the comment form is closed at this time.