请问下使用PHP如何获取某个月的所有日期


图片描述

就像上面图一样。第一列的日期不是存在数据库的。其他的列字段都是数据库里的数据。
存在数据库里的数据比较好查询,现在的问题是第一列的日期要如何用php获得。

想获取到日期后把每天都存到一个数组里,然后我到视图页面输出出来。是用的CI框架

日期 ci

奶瓶的霸气 10 years, 11 months ago

由于官方现在比较推荐使用 DateTime 类来做时间操作,现补上一个另外一个版本。不过似乎这个在 PHP>=5.3 上才有很好的支持,所以如果要兼容老版的可以继续使用 date 方法。


 <?php
// http://3v4l.org/jK99E
// function that recommended by offical
function getMonthDays($month = "this month", $format = "Y-m-d", $dateTimeZone = false) {
    if(!$dateTimeZone) $dateTimeZone = new DateTimeZone("Asia/Shanghai");
    $start = new DateTime("first day of $month", $dateTimeZone);
    $end = new DateTime("last day of $month", $dateTimeZone);

    $days = array();
    for($time = $start; $time <= $end; $time = $time->modify("+1 day")) {
        $days[] = $time->format($format);
    }
    return $days;
}

$thisMonthDays = getMonthDays();
$octMonthDays = getMonthDays("2014-10");

print_r($thisMonthDays);
print_r($octMonthDays);



 <?php
// http://3v4l.org/vZqHK
// function that compatible well
function getMonthDays($month = "this month", $format = "Y-m-d") {
    $start = strtotime("first day of $month");
    $end = strtotime("last day of $month");
    $days = array();
    for($i=$start;$i<=$end;$i+=24*3600) $days[] = date($format, $i);
    return $days;
}

$thisMonthDays = getMonthDays();
$octMonthDays = getMonthDays("2014-10");

print_r($thisMonthDays);
print_r($octMonthDays);

agwcc answered 10 years, 11 months ago

Your Answer