获取特定年份的月份列表及其开始日期和上次日期

时间:2016-07-31 02:02:41

标签: php arrays calendar mktime

我希望从表格中提交年份的特定年份列表。月份必须是月份的开始日期和最后日期。

$year = $_POST['year'];
$current_year = date('Y');

for ($m=1;$m<=12;$m++)
{$month = date("F", mktime(0,0,0,$m,1,$year));
$nmonth = date("m",strtotime($month));
$days = cal_days_in_month(CAL_GREGORIAN,$nmonth,$year);
$sdate = mktime(0, 0, 0, $nmonth, 1, $year);
$edate = mktime(0, 0, 0, $nmonth, $days, $year);
//$edate = date("Y-m-t", strtotime($sdate));
echo strftime("$month $year").'  -  '.'Start date '.''.strftime(" %Y-%m-%d",     $sdate).'  '.'End date '.''.$edate.'   -   '.strtoupper(substr($month, 0, 3)).date("y",mktime(0,0,0,$nmonth,1,$year)).$days.'<br>';
//echo $month.' '.$days.' '.$sdate.' '.$edate.'<br>';
}

<body>
<form id="period" name="period" method="post" action="create_period.php">

  <input type="text" name="year" id="year" />

  <label>
   <input type="submit" name="button" id="submit" value="Create Period" />
   </label>
   <input type="hidden" name="id" id="id" />
</form>

</body>

1 个答案:

答案 0 :(得分:2)

您可以像这样使用DatePeriod

$year = 2015;

$period = new DatePeriod(
     (new DateTime())->setDate($year, 1, 1), //Start at 2015-01-01
     new DateInterval('P1M'), //Step is 1 month
     (new DateTime())->setDate($year+1, 1, 1) //End at 2016-01-01
);

foreach($period as $date){
    $firstDay = $date->modify('first day of this month')->format("Y/m/d") ;
    $lastDay = $date->modify('last day of this month')->format("Y/m/d") ;

    echo "$firstDay - $lastDay <br>";
}

演示: https://3v4l.org/CidUa