PHP find previous monday from a date

This small function returns the date (with the format you want) of the previous monday from a given date. If…

Dicembre 3, 2010

This small function returns the date (with the format you want) of the previous monday from a given date. If given date is empty it gets the today date:

// usage:
// last monday: $d = findMonday();
// last monday before 31-12-2010: $d = findMonday("2010-12-31");
// last monday before 31-12-2010 with a specific format: $d = findMonday("2010-12-31","m/d/Y");

function findMonday($d="",$format="Y-m-d") {
	if($d=="") $d=date("Y-m-d");
	$delta = date("w",strtotime($d)) - 1;
	if ($delta <0) $delta = 6;
	return date($format, mktime(0,0,0,date('m'), date('d')-$delta, date('Y') ));
}

Author

PHP expert. Wordpress plugin and theme developer. Father, Maker, Arduino and ESP8266 enthusiast.

Comments on “PHP find previous monday from a date”

6 thoughts

  1. Jon ha detto:

    You need to pass the date to the date() calls on the last row, otherwise the returned date will always be the current date minus delta, rather than the specified date minus the delta.

  2. Dan ha detto:

    What about:

    function findMonday($d = “”, $format = “Y-m-d”) {
    return date($format, strtotime(‘last monday’, $d));
    }

    ?

  3. davide ha detto:

    Thank you! Just what I need to complete my sw.

  4. Cyndi ha detto:

    This worked better for me
    public function findMonday($datePassed=””,$format=”Y-m-d”) {
    $dateObj = new DateTime($datePassed);
    $dayOfWeek = $dateObj->format(“N”);
    while($dayOfWeek 1){
    $dateObj->sub(new DateInterval(‘P1D’));
    $dayOfWeek = $dateObj->format(“N”);
    }
    return $dateObj->format(“Y-m-d”);
    }

  5. Giulio Pons ha detto:

    really good! it works?

  6. Dave ha detto:

    Doesn’t work. You probably should have tested this before posting it.

    This, however, does work:
    function findMonday($d=””,$format=”Y-m-d”) {
    if($d==””) $d=date(“Y-m-d”);
    $dparts = explode(“-“,$d);
    $mydate = mktime(12,0,0,$dparts[1],$dparts[2],$dparts[0]);
    $weekday = ((int)date( ‘w’, $mydate ) + 6 ) % 7;
    $prevmonday = $mydate – $weekday * 24 * 3600;
    return date($format,$prevmonday);
    }

Comments are closed

Recommended

The Quantcast CMP broke my sites

A javascript error in CMP blocks my site.

Maggio 19, 2023

WP Gutenberg notes

Collection of notes and thoughts on Wordpress Gutenberg blocks development.

Gennaio 9, 2023

Optimizing LCP, Largest Contentful Paint result

Notes about Core Web Vitals optimization challenge

Gennaio 4, 2023

Find values recursively inside complex json objects in PHP

A PHP function to to quickly search complex, nested php structures for specific values.

Dicembre 18, 2022

Scroll to DIV by ID without jQuery

Use scrollIntoView instead of jQuery animate.

Dicembre 16, 2022