dougan1465 2016-07-31 02:02
浏览 96
已采纳

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

I want to get a list of months from a particular year when the year is submitted from a form. The months must come with the start date and the last date of the month.

$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条回答 默认 最新

  • duan19750503 2016-07-31 02:15
    关注

    You can use DatePeriod like this:

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

    Demo: https://3v4l.org/CidUa

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能