开发者

How to find start and end date of last 4 months including current in php

开发者 https://www.devze.com 2023-03-20 19:21 出处:网络
I want to get the start and end dates on last 4 months including current开发者_开发百科 month.Please help.

I want to get the start and end dates on last 4 months including current开发者_开发百科 month.Please help.

Regards Jos


With PHP 5.2+, you can use DateTime and DateInterval to solve this problem:

Example:

<?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'))));
?>

you can add or remove months ... and you will get accurate results


I'd do it this way...

<?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>";
}

?>
0

精彩评论

暂无评论...
验证码 换一张
取 消