要查找该月的最后一天,您可以使用t 作为提供给date() 函数的格式参数。要查找每月 15 日,请使用 mktime 生成时间并转换为具有所需输出格式的日期。
/* Initial date and duration of processing */
$start = '2019-01-21';
$months = 4;
/* reduce start date to it's constituent parts */
$year = date('Y',strtotime($start));
$month = date('m',strtotime($start));
$day = date('d',strtotime($start));
/* store results */
$output=array();
for( $i=0; $i < $months; $i++ ){
/* Get the 15th of the month */
$output[]=date('Y-m-d', mktime( 0, 0, 0, $month + $i, 15, $year ) );
/* Get the last day of the calendar month */
$output[]=date('Y-m-t', mktime( 0, 0, 0, $month + $i, 1, $year ) );
}
/* use the results somehow... */
printf('<pre>%s</pre>',print_r($output,true));
输出:
Array
(
[0] => 2019-01-15
[1] => 2019-01-31
[2] => 2019-02-15
[3] => 2019-02-28
[4] => 2019-03-15
[5] => 2019-03-31
[6] => 2019-04-15
[7] => 2019-04-30
)
如果,正如下面的评论所暗示的,您希望日期从月底开始,而不是每月 15 日,只需更改循环中的顺序,将计算的日期添加到输出数组...
for( $i=0; $i < $months; $i++ ){
/* Get the last day of the calendar month */
$output[]=date('Y-m-t', mktime( 0, 0, 0, $month + $i, 1, $year ) );
/* Get the 15th of the month */
$output[]=date('Y-m-d', mktime( 0, 0, 0, $month + $i, 15, $year ) );
}
输出:
Array
(
[0] => 2019-01-31
[1] => 2019-01-15
[2] => 2019-02-28
[3] => 2019-02-15
[4] => 2019-03-31
[5] => 2019-03-15
[6] => 2019-04-30
[7] => 2019-04-15
)
以示例结果的精确格式输出结果
$format=(object)array(
'last' => 't-M-y',
'15th' => 'd-M-y'
);
for( $i=0; $i < $months; $i++ ){
/* Get the last day of the calendar month */
$output[]=date( $format->{'last'}, mktime( 0, 0, 0, $month + $i, 1, $year ) );
/* Get the 15th of the month */
$output[]=date( $format->{'15th'}, mktime( 0, 0, 0, $month + $i, 15, $year ) );
}
输出:
Array
(
[0] => 31-Jan-19
[1] => 15-Jan-19
[2] => 28-Feb-19
[3] => 15-Feb-19
[4] => 31-Mar-19
[5] => 15-Mar-19
[6] => 30-Apr-19
[7] => 15-Apr-19
)