php獲取指定日期,前一天、前一周、前一個月、前一年,后一天,后一周,前一個月,前一年


dump(date('Y-m-d', strtotime('2018-10-1 +1 day')));

dump(date('Y-m-d', strtotime('2018-10-1 +1 week')));

dump(date('Y-m-d', strtotime('2018-10-1 +1 month')));

dump(date('Y-m-d', strtotime('2018-10-1 +1 year')));

dump(date('Y-m-d', strtotime('2018-10-1 -1 day')));

dump(date('Y-m-d', strtotime('2018-10-1 -1 week')));

dump(date('Y-m-d', strtotime('2018-10-1 -1 month')));

dump(date('Y-m-d', strtotime('2018-10-1 -1 year')));

同理,把2018-10-1換成變量,就可以做很多事了!

ps 由於每個月份的天數不一樣 +/- 1 month 特殊日期會有誤差

//獲取上一個月日期方法  

public function getBeforeMonthDate($currentDate)
{
    $currentMonthDay = date('t', strtotime($currentDate));
    $currentDay      = date('d', strtotime($currentDate));
    $yearMonth       = date('Y-m', strtotime($currentDate));
    $beforeMonth     = date('Y-m-d', strtotime("$yearMonth -1 month"));
    $beforeMonthDay  = date('t', strtotime($beforeMonth));
    if ($beforeMonthDay < $currentMonthDay && $beforeMonthDay < $currentDay) {
        $beforeDate = date("Y-m-d", strtotime("last day of -1 month", strtotime($currentDate)));
    } else {
        $beforeDate = date('Y-m-d', strtotime("$currentDate -1 month"));
    }
    return $beforeDate;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM