dt20081409 2014-12-01 18:42
浏览 113
已采纳

DateTime :: diff year不起作用

I cannot figure out why the year (y) of DateTime::diff isn't working.

Here is what I have

    $startDate = new DateTime('2009-12-01');
    $endDate = new DateTime('2014-12-01');
    // $current = $workid->current;     

    if($current) // currently works at this job
    {
        // $endDate = new DateTime(); // current date/time
    }

    $diff = $endDate->diff($startDate);

    if($diff->y = 0)
    {
        if($diff->m > 1)
        {
            $string = $diff->m . ' months';
        }
        else
        {
            $string = '1 month';
        }
    }
    elseif ($diff->y = 1)
    {
        if($diff->m > 1)
        {
            $string = '1 year ' . $diff->m . ' months';
        }
        else
        {
            $string = '1 year 1 month';
        }
    }
    else
    {
        if($diff->m > 1)
        {
            $string = $diff->y . ' years ' . $diff->m . ' months';
        }
        else
        {
            $string = $diff->y . ' years 1 month';
        }
    }

    print_r($diff);

It outputs

DateInterval Object ( [y] => 1 [m] => 0 [d] => 0 [h] => 0 [i] => 0 [s] => 0 [weekday] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [invert] => 1 [days] => 1826 [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0 )

The [y] should say 5 but it says 1 no matter what year I change the $startDate year to.

Here is my php -v output

PHP 5.5.9-1ubuntu4.5 (cli) (built: Oct 29 2014 11:59:10)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies
    with Zend OPcache v7.0.3, Copyright (c) 1999-2014, by Zend Technologies
  • 写回答

1条回答 默认 最新

  • doudi2520 2014-12-01 18:51
    关注

    Change your = in your conditions to == (all)

    Otherwise you make a assignment and the last one is $diff->y = 1 so that's why the output is 1!

    You have to change it to this: $diff->y == 1 So it's comparing to this value

    For further information about Comparison Operator take a look at: http://php.net/manual/en/language.operators.comparison.php

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

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来