首頁  >  文章  >  後端開發  >  php strtotime 如何取得上週一的時間呢? -1 monday不對

php strtotime 如何取得上週一的時間呢? -1 monday不對

WBOY
WBOY原創
2016-10-17 09:30:102296瀏覽

-1 monday輸出是這週一的時間,很奇怪

回覆內容:

-1 monday輸出是這週一的時間,很奇怪

因為老外認為「this monday」是下週一,「last monday」是本週一
直接"-2 monday"就好了,或者"monday last week"

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

-7 days

last week

通常分兩步走,先取得上週的任一天,再去找周一,就像求月末是找到下個月的1號,然後-1 day一樣。

這個還是寫一個通用的方法吧

<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')得到當前週幾,由於週一至週六分別是1-6,週日是0。當數值為0的時候,上週一是13天前。其餘就是date('w')+6天前。

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

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

這裡看到了文檔連結描述

echo "上個週一:".date("Y-m-d",strtotime("last Monday"))."
";

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

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

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn