用PHP獲取本周第一天和最后一天,網上有很多方法,但是太麻煩,或者有bug,這是用php自帶的DateTime類實現的方法,比較簡單:
- //本周的第一天和最后一天
- $date=new DateTime();
- $date->modify('this week');
- $first_day_of_week=$date->format('Y-m-d');
- $date->modify('this week +6 days');
- $end_day_of_week=$date->format('Y-m-d');
經過測試modity不知道是用做什么了,于時找了另兩個例子,代碼如下:
- //這個星期的星期一
- // @$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];
- }
- //這個星期的星期天
- // @$timestamp ,某個星期的某一個時間戳,默認為當前時間
- // @is_return_timestamp ,是否返回時間戳,否則返回時間格式
- function this_sunday($timestamp=0,$is_return_timestamp=true){
- static $cache ;
- $id = $timestamp.$is_return_timestamp;
- if(!isset($cache[$id])){
- if(!$timestamp) $timestamp = time();
- $sunday = this_monday($timestamp) + /*6*86400*/518400;
- if($is_return_timestamp){
- $cache[$id] = $sunday;
- }else{
- $cache[$id] = date('Y-m-d',$sunday);
- }
- }
- return $cache[$id];
- }
新聞熱點
疑難解答