1. 程式人生 > >PHP 時間的用法集合

PHP 時間的用法集合

//獲取下個月此時是時間戳
date("Y-m-d H:i:s",strtotime("+1 month"));
//獲取今天是本月的第幾天
date('j',time());
//獲取今天是本週的第幾天
date('w',time());
//獲取當月總天數
date('t', time());
//獲取當前日期
date('d', time());

public function index()
    {
        $month = $this->getThisMonth();
        $week = $this->getThisWeek();
        dump($month);
        echo "================================================";
        dump($week);
    }

    /**
     * 獲取某月所有時間(預設本月)
     */
    public function getThisMonth($time = '', $format='Y-m-d'){
        $time = $time != '' ? $time : time();
        //獲取當前日期
        $week = date('d', $time);
        $date = [];
        //date('t', $time) 獲取當月總天數
        for ($i=1; $i<= date('t', $time); $i++){
            $date[$i] = date($format ,strtotime(  $i-$week .' days', $time));
        }
        return $date;
    }

    /**
     * 獲取某周所有日期(預設本週)
     */
    public function getThisWeek($time = '', $format='Y-m-d'){
        $time = $time != '' ? $time : time();
        //獲取當前周幾
        $week = date('w', $time);
        $date = [];
        for ($i=1; $i<=7; $i++){
            $date[$i] = date($format ,strtotime( $i-$week .' days', $time));
        }
        return $date;
    }

 /**
  * 獲取兩個日期之間的所有日期
  */
    public function getDatesBetweenTwoDays($startDate,$endDate){
    $dates = [];
    if(strtotime($startDate)>strtotime($endDate)){
        //如果開始日期大於結束日期,直接return 防止下面的迴圈出現死迴圈
        return $dates;
    }elseif($startDate == $endDate){
        //開始日期與結束日期是同一天時
        array_push($dates,$startDate);
        return $dates;
    }else{
        array_push($dates,$startDate);
        $currentDate = $startDate;
        do{
            $nextDate = date('Y-m-d', strtotime($currentDate.' +1 days'));
            array_push($dates,$nextDate);
            $currentDate = $nextDate;
        }while($endDate != $currentDate);
        return $dates;
    }
}

列印結果: