IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    关于时间加减的测试

    chaoyun发表于 2014-12-11 07:09:52
    love 0

    下面是最易犯错的代码:

    $date_start = mktime(0, 0, 0, 1, 1, 2010);
    $date_end = mktime(0, 0, 0, 4, 15, 2014);

    for($tm = $date_end; $tm >= $date_start; $tm -= 86400)
    {
    $year = date(‘Y’, $tm);
    $month = date(‘m’, $tm);
    $day = date(‘d’, $tm);

    echo date(‘Y-m-d H:i:s’, $tm) . “\n”;
    }

    下面是正确的代码:

    for($tm = $date_end; $tm >= $date_start; $tm -= 40000)
    {

    $year = date(‘Y’, $tm);
    $month = date(‘m’, $tm);
    $day = date(‘d’, $tm);

    echo date(‘Y-m-d H:i:s’, $tm) . “\n”;

    $tm = mktime(0, 0, 0, $month, $day, $year);
    }

    或者下面的代码也正确:

    $dt = new DateTime(’2014-04-15′);
    for($dt = new DateTime(“@$date_end”); date_timestamp_get($dt) >= $date_start; $dt = date_sub($dt, date_interval_create_from_date_string(’1 day’)))
    {
    $tm = date_timestamp_get($dt);
    $year = date(‘Y’, $tm);
    $month = date(‘m’, $tm);
    $day = date(‘d’, $tm);

    echo date(‘Y-m-d H:i:s’, $tm) . “\n”;

    $dt = new DateTime(date(‘Y-m-d 00:00:00′, $tm));
    }



沪ICP备19023445号-2号
友情链接