php strtotime “last monday” if today is monday?

后端 未结 8 1746
攒了一身酷
攒了一身酷 2020-11-30 03:45

I want to use strtotime(\"last Monday\").

The thing is, if today IS MONDAY, what does it return? It seems to be returning the date for the monday of la

8条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 04:24

    Late answer, but I thought I would post up this answer (which is actually from a different but related question). It handles the scenario in the question:

    function last_monday($date) {
        if (!is_numeric($date))
            $date = strtotime($date);
        if (date('w', $date) == 1)
            return $date;
        else
            return strtotime(
                'last monday',
                 $date
            );
    }
    
    echo date('m/d/y', last_monday('8/14/2012')); // 8/13/2012 (tuesday gives us the previous monday)
    echo date('m/d/y', last_monday('8/13/2012')); // 8/13/2012 (monday throws back that day)
    echo date('m/d/y', last_monday('8/12/2012')); // 8/06/2012 (sunday goes to previous week)
    

    try it: http://codepad.org/rDAI4Scr

    ... or a variation that has sunday return the following day (monday) rather than the previous week, simply add a line:

     elseif (date('w', $date) == 0)
        return strtotime(
            'next monday',
             $date
        );
    

    try it: http://codepad.org/S2NhrU2Z

    You can pass it a timestamp or a string, you'll get back a timestamp

    Documentation

    • strtotime - http://php.net/manual/en/function.strtotime.php
    • date - http://php.net/manual/en/function.date.php

提交回复
热议问题