Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Reliable PHP function to return Monday for week
<?php
/**
* Find the starting Monday for the given week (or for the current week if no date is passed)
*
* This is required as strtotime considers Sunday the first day of a week,
* making strtotime('Monday this week') on a Sunday return the adjacent Monday
* instead of the previous one.
*
* @param string|\DateTime|null $date
* @return \DateTime
*/
function getStartOfWeekDate($date = null)
{
if ($date instanceof \DateTime) {
$date = clone $date;
} else if (!$date) {
$date = new \DateTime();
} else {
$date = new \DateTime($date);
}
$date->setTime(0, 0, 0);
if ($date->format('N') == 1) {
// If the date is already a Monday, return it as-is
return $date;
} else {
// Otherwise, return the date of the nearest Monday in the past
// This includes Sunday in the previous week instead of it being the start of a new week
return $date->modify('last monday');
}
}
@haziqAhmed7

This comment has been minimized.

Copy link

commented Oct 23, 2016

great piece of code...
you save my day buddy!!!

@tianmarin

This comment has been minimized.

Copy link

commented Jan 18, 2017

Just AWESOME!
very simple, but does what it must

@achasseux

This comment has been minimized.

Copy link

commented Feb 27, 2018

👍

@panmitz

This comment has been minimized.

Copy link

commented Mar 25, 2018

Thanks mate. Nice snippet.

@dkimery256

This comment has been minimized.

Copy link

commented Jan 25, 2019

Thanks!

@shraddha27

This comment has been minimized.

Copy link

commented May 8, 2019

Thank you so much. You saved my day. May God Bless You always

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.