【问题标题】:Issues with Dates日期问题
【发布时间】:2015-05-12 01:20:28
【问题描述】:

我需要从当前开始每周获取周一至周日的范围。

这是我想出的:

$range = 0;
$weekNumber =  date("W", strtotime(date('l j  F Y') . '  ' . ($range) . ' days'));
$weekYear =  date("Y", strtotime(date('l j  F Y') . '  ' . ($range) . ' days'));

$week_array = getWeekDates($weekNumber, $weekYear);

function getWeekDates($week, $year) {
    $dto = new DateTime();
    $ret['mon'] = $dto->setISODate($year, $week)->format('Y-m-d');
    $ret['tue'] = $dto->modify('+1 days')->format('Y-m-d');
    $ret['wed'] = $dto->modify('+1 days')->format('Y-m-d');
    $ret['thu'] = $dto->modify('+1 days')->format('Y-m-d');
    $ret['fri'] = $dto->modify('+1 days')->format('Y-m-d');
    $ret['sat'] = $dto->modify('+1 days')->format('Y-m-d');
    $ret['sun'] = $dto->modify('+1 days')->format('Y-m-d');
    return $ret;
}

它可以在我的本地 WampServer (5.3.4) 上运行,但是当我尝试在 Godaddy (5.2.17) 上运行它时,出现此错误:

致命错误:在 /home/.....php 中的非对象上调用成员函数 format() 在线 ($ret['mon'] = $dto->setISODate($年,$week)->format('Y-m-d');)

【问题讨论】:

  • godaddy 和本地 wamp 服务器上的 php 版本是什么?可能不兼容

标签: php date fatal-error


【解决方案1】:

根据The Documentation,,“setISODate”和“modify”的返回值从 NULL 更改为从 5.3 开始的 DateTime。这就是为什么它可以在较新的 php 环境中工作但不能在较旧的环境中工作的原因。

要使您的代码兼容,请将代码更改为以下内容:

$dto->setISODate($year, $week);
$ret['mon'] = $dto->format('Y-m-d');
$dto->modify('+1 days');
$ret['tue'] = $dto->format('Y-m-d');
//so forth for rest of days

下面是函数的另一种写法:

function getWeekDates($week, $year) {
    $dto = new DateTime();
    $dto->setISODate($year, $week);
    $keys = array('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun');
    $ret = array();
    for($i = 0; $i < 7; $i++) {
        $ret[$keys[$i]] = $dto->format('Y-m-d');
        $dto->modify('+1 days');
    }
    return $ret;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多