簡體   English   中英

DateTime :: diff年不工作

[英]DateTime::diff year is not working

我無法弄清楚為什么DateTime::diff的年份(y)無法正常工作。

這是我所擁有的

    $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);

輸出

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 )

[y]應該說5但是無論我將$startDate年更改為哪一年,它都說1

這是我的php -v輸出

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

將您的條件中的=更改為== (全部)

否則,您進行賦值,最后一個賦值為$diff->y = 1因此這就是輸出為1的原因!

您必須將其更改為: $diff->y == 1因此它正在與此值進行比較

有關比較運算符的更多信息,請訪問: http : //php.net/manual/en/language.operators.comparison.php

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM