如何找到开始和结束日期的最后4个月,包括当前在php



我想获得最近4个月的开始和结束日期,包括当前月份。请帮助。

的问候乔斯

在PHP 5.2+中,您可以使用DateTimeDateInterval来解决这个问题:

例子:

<?php
$date = new DateTime('first day of this month 3 months ago');
// Loop 4 times.
for ( $i = 0; $i < 4; $i++ )
{
  echo 'Start: ' . $date->format('Y-m-d') . PHP_EOL;
  echo 'End: ' . $date->format('Y-m-t') . PHP_EOL;
  // Add 1 month.
  $date->add(new DateInterval('P1M'));
}
<?php
// start day of current month
echo date("m/d/Y", strtotime(date('m').'/01/'.date('Y').' 00:00:00'));
// end day of current month
echo date("m/d/Y", strtotime('-1 second',strtotime('+1 month',strtotime(date('m').'/01/'.date('Y').' 00:00:00'))));
?>

您可以添加或删除月份…你会得到准确的结果

我会这样做…

<?php
// current day to start with
$start = mktime(0,0,0,date('m'), date('d'), date('Y'));;
// loop through the current and last four month
for ($i = 0; $i <=4; $i++) {
    // calculate the first day of the month
    $first = mktime(0,0,0,date('m',$start) - $i,1,date('Y',$start));
    // calculate the last day of the month
    $last = mktime(0, 0, 0, date('m') -$i + 1, 0, date('Y',$start));
    // now some output...
    echo date('Y-m-d',$first) . " - ".date('Y-m-d',$last). "<br>";
}
?>

相关内容

最新更新