简体   繁体   English

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

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

I want to get the start and end dates on last 4 months including current month.Please help.我想获得过去 4 个月的开始和结束日期,包括当前月份。请帮忙。

Regards Jos问候乔斯

With PHP 5.2+, you can use DateTime and DateInterval to solve this problem:使用 PHP 5.2+,您可以使用DateTimeDateInterval来解决这个问题:

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

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何获取时间戳:当年季度开始/结束,上季度开始/结束,从 PHP 中的指定日期开始 - How to get timestamp of: current year quarter start/end, last quarter start/end, from specified date in PHP 如何在 php 中获取给定日期范围的月份的开始日期和结束日期 - How to get start and end date of months of a given range of date in php php,根据开始日期和月数获取结束日期 - php, get an end date based on start date and number of months 如何在PHP中显示当前一周的开始和结束日期? - How do I display the start and end date of the current week in PHP? PHP 从选定月份中获取一周的开始和结束日期 - PHP get start and end date of a week from selected months PHP获取包含年,月和日的数组,并指定开始和结束日期 - PHP Getting array with years, months and dates given a start and end date PHP-从当前日期算起最近6个月 - PHP- get the last 6 months from the current date 输入“结束日期”是在“开始日期”输入之后的10个月。 [PHP] - Check End Date input is 10 months after Start Date input. [PHP] 如何循环获得过去十二个月的开始和结束的Unix时间? - How can I get unix times for the start and end of last twelve months in a loop? 通过选择从开始日期开始的周数或月数来自动结束日期 - Auto end date by selecting number of weeks or months from start date
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM