I am trying to get the date of Monday from a specific date. I try to use
JavaScript
x
strtotime("last monday")
But it’s giving me current last Monday date not from a specific date. Like I want to know the last Monday date on 2020-10-11 which is 2020-10-05
Advertisement
Answer
You can use the class DateTime
to create an object at the desired date, and then modify it :
JavaScript
$date = new DateTime('2020-10-11');
$date->modify('last monday');
echo $date->format('Y-m-d'); // output is 2020-10-05
As pointed jspit in comments, if the current date is monday and then if this date should be returned, a simple check can be added to avoid returning the wrong date :
JavaScript
$date = new DateTime('2020-10-11');
if ($date->format('N') != 1) // If the date isn't already monday
$date->modify('last monday');
echo $date->format('Y-m-d'); // output is 2020-10-05