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

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

报告相同问题?

悬赏问题

  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据