PHP strtotime and date functions are used.
1. Obtain the first day of the month in which the specified date resides
function getMonthFirstDay($date) {
return date('Y-m-01',strtotime($date));
}
Copy the code
2. Obtain the last day of the month in which the specified date resides
function getMonthEndDay($date) {
$firstDay = getMonthFirstDay($date);
return date("Y-m-d",strtotime("$firstDay +1 month -1 day"));
}
Copy the code
3. Get the first and last day of each month between the specified dates
function splitMonths($startTime,$endTime) {
if (strtotime($startTime) > strtotime($endTime)) {
return false;
}
$res = array();
$startDay = date('Y-m-d',strtotime($startTime));
$firstEndDay = getMonthEndDay($startTime);
$lastStartDay = getMonthFirstDay($endTime);
$lastEndDay = date('Y-m-d',strtotime($endTime));
//$res[] = array($startDay,$firstEndDay);
while (strtotime($startDay) < strtotime($lastStartDay)) {
$endDay = getMonthEndDay($startDay);
$res[] = array($startDay,$endDay);
$startDay = date('Y-m-01',strtotime("$startDay +1 month"));
}
$res[] = array($startDay,$lastEndDay);
return $res;
}
Copy the code
For example, enter start_date=2017-02-15&end_date=2017-05-25
array(4) {
[0]=>
array(2) {
[0]=>
string(10) "2017-02-15"
[1]=>
string(10) "2017-02-28"
}
[1]=>
array(2) {
[0]=>
string(10) "2017-03-01"
[1]=>
string(10) "2017-03-31"
}
[2]=>
array(2) {
[0]=>
string(10) "2017-04-01"
[1]=>
string(10) "2017-04-30"
}
[3]=>
array(2) {
[0]=>
string(10) "2017-05-01"
[1]=>
string(10) "2017-05-25"
}
}
Copy the code