Home >Backend Development >PHP Tutorial >Get the dates of last month, next month, and this month under PHP_PHP Tutorial
Because I need to get the dates of last month, next month, and this month for my work, I found the implementation code from the website. I would like to share it with friends who need it
When I was writing a program today, I suddenly discovered a function I wrote a long time ago to get the number of days in a month. It’s a classic switch version. But when I got the number of days in the previous month, I just changed the month to -1. I guess I was too sleepy at the time. Let’s see again. It gave me a creepy feeling, and I originally wanted to deal with it again, but then I thought there must be some super convenient method, so I found the version below and made some minor modifications. Get the date of this month: The code is as follows: function getMonth($date){ $firstday = date("Y-m-01",strtotime($date)); $lastday = date("Y-m-d",strtotime("$firstday +1 month -1 day")); Return array($firstday,$lastday); } $firstday is the first day of the month. If $date is 2014-2, $firstday will be 2014-02-01. Then add one month to $firstday to get 2014-03-01, and subtract one day to get 2014- 02-28, using date() and strtotime() is so convenient. Get the date of last month: The code is as follows: function getlastMonthDays($date){ $timestamp=strtotime($date); $firstday=date('Y-m-01',strtotime(date('Y',$timestamp).'-'.(date('m',$timestamp)-1).'-01')); $lastday=date('Y-m-d',strtotime("$firstday +1 month -1 day")); Return array($firstday,$lastday); } The date of the previous month needs to be obtained first by getting a timestamp, and then adding -1 to the month is OK. The super smart date() will convert things like 2014-0-1 into 2013-12-01, which is so cool. Get the date of next month: The code is as follows: function getNextMonthDays($date){ $timestamp=strtotime($date); $arr=getdate($timestamp); If($arr['mon'] == 12){ $year=$arr['year'] +1; $month=$arr['mon'] -11; $firstday=$year.'-0'.$month.'-01'; $lastday=date('Y-m-d',strtotime("$firstday +1 month -1 day")); }else{ $firstday=date('Y-m-01',strtotime(date('Y',$timestamp).'-'.(date('m',$timestamp)+1).'-01')); $lastday=date('Y-m-d',strtotime("$firstday +1 month -1 day")); } Return array($firstday,$lastday); } The code for next month's date seems a bit longer, because date() cannot convert something like 2014-13-01, it will go back to 1970 directly, so we need to deal with the issue of December in the front, except for December, just use the month directly. +1 is OK. Generally speaking, it is very convenient, and the date function is too powerful.