我想创建一个这样的表...
Oct-01 | Oct-02 | Oct-03 | Oct-04 | etc etc
使用现在的任何月份。
我用这个来获得第一天...
$first = date('01-m-Y',strtotime('this month'));
我怎样才能增加本月的天数?
使用cal_days_in_month(CAL_GREGORIAN, date(j), 2013)
?
但是如何增加第一天。我尝试在strtotime
中使用"+1 天",但没有任何反应。
有什么想法吗?
PHP的DateTime
类可以在这里使用。您无需使用cal_days_in_month
函数来计算一个月中的天数 - DateTime
自动处理它。而且它更干净,支持广泛的日期。
方法如下:
$start = new DateTime('first day of this month');
$end = new DateTime('first day of this month + 1 month');
$period = new DatePeriod($start, new DateInterval('P1D'), $end);
foreach($period as $day){
echo $day->format('M-d')."<br/>";
}
演示!
我更喜欢使用DateTime对象:
$date = new DateTime();
$date->modify('first day of this month');
$days = array();
for($i = 1; $i <= $date->format('t'); $i++){
$days[] = $date->format('M-d');
$date->modify('+1 day');
}
您还可以将整个日期对象添加到数组中,以便以后可以灵活地根据需要使用它。
<?php
$days = array();
$maxDay = cal_days_in_month(CAL_GREGORIAN, date('j'), date('Y'));
for($i = 1; $i<$maxDay; ++$i) {
$days[] = sprintf(date('M')."-%1$02d", $i);
}
echo "<pre>";
var_dump($days);
现在你可以用$days阵列做任何你喜欢的事情......
http://phpfiddle.org/lite/code/fd1-1r2