Home  >  Article  >  Backend Development  >  How to get the time of last Monday in php strtotime? -1 monday is wrong

How to get the time of last Monday in php strtotime? -1 monday is wrong

WBOY
WBOYOriginal
2016-10-17 09:30:102342browse

-1 monday output is this Monday, which is very strange

Reply content:

-1 monday output is this Monday, which is very strange

Because foreigners think "this monday" is next Monday and "last monday" is this Monday
Just use "-2 monday", or "monday last week"

date('Y-m-d', strtotime('-' . (6+date('w')) . ' days'));

-7 days

last week

Usually done in two steps, first get any day of the last week, and then find Monday, just like finding the end of the month is to find the 1st of the next month, and then -1 day.

Let’s write a general method for this

<code>function last_monday($timestamp=0,$is_return_timestamp=true){ 
    static $cache ; 
    $id = $timestamp.$is_return_timestamp; 
    if(!isset($cache[$id])){ 
        if(!$timestamp) $timestamp = time(); 
        $thismonday = this_monday($timestamp) - /*7*86400*/604800; 
        if($is_return_timestamp){ 
            $cache[$id] = $thismonday; 
        }else{ 
            $cache[$id] = date('Y-m-d',$thismonday); 
        } 
    } 
    return $cache[$id]; 
}</code>

date('w') gets the current day of the week, since Monday to Saturday are 1-6 respectively, and Sunday is 0. When the value is 0, last Monday was 13 days ago. The rest is date('w')+6 days ago.

<code>$days = date('w')==0?13:date('w')+6;

echo date('Y-m-d',time()-$days*86400);</code>

See the document link description here

echo "Last Monday:".date("Y-m-d",strtotime("last Monday"))."
";

$time = strtotime("-7 day");

$timetest =date("Y-m-d h:i:sa", $time);

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn