PHP CodeBase: 求最近一個週一和上週一的日期

有時候,會有這麼一些需求:在每週的週一會更新一些內容,那麼我要獲取本週週一的數據,或者上週週一的數據,那麼就須要知道本週或上週週一的日期了。對於程序來講,需求就變成了:這周的週一是幾號?或者說,上週一是幾號?php

先來求一下本週週一的日期函數

$ts = time();

$this_monday = this_monday($ts);
echo date('Y-m-d H:i:s', $this_monday);

//這個星期的星期一  
// @$timestamp ,某個星期的某一個時間戳,默認爲當前時間  
// @is_return_timestamp ,是否返回時間戳,不然返回時間格式  
function this_monday($timestamp=0,$is_return_timestamp=true){  
    static $cache ;  
    $id = $timestamp.$is_return_timestamp;  
    if(!isset($cache[$id])){  
        if(!$timestamp) $timestamp = time();  
        $monday_date = date('Y-m-d', $timestamp-86400*date('w',$timestamp)+(date('w',$timestamp)>0?86400:-/*6*86400*/518400));  
        if($is_return_timestamp){  
            $cache[$id] = strtotime($monday_date);  
        }else{  
            $cache[$id] = $monday_date;  
        }  
    }  
    return $cache[$id];  
  
}

求上週一的函數則爲:this

$ts = time();

$last_monday = last_monday($ts);
echo date('Y-m-d H:i:s', $last_monday);

//上週一  
// @$timestamp ,某個星期的某一個時間戳,默認爲當前時間  
// @is_return_timestamp ,是否返回時間戳,不然返回時間格式  
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];  
}
相關文章
相關標籤/搜索