2014-12-01 102 views
0

我不明白为什么DateTime::diff年(y)不起作用。DateTime ::差异年不工作

这里是我有什么

$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但它说1不管哪一年我改变$startDate年来。

这里是我的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 
+0

[我得到不同的结果(https://开头的eval .in/229044) – 2014-12-01 18:44:40

+0

我正在使用Laravel,如果这有所作为。 – 2014-12-01 18:45:26

+0

它应该不是因为你没有在这里使用该框架的代码 – 2014-12-01 18:45:50

回答

1

在你的情况你=更改为==(全部)

否则,你犯了一个任务,最后一个是$diff->y = 1所以这就是为什么输出是1!

你必须把它改成这样:$diff->y == 1所以它比较这个值

有关比较运算符的详细信息看一看:http://php.net/manual/en/language.operators.comparison.php

+0

井当当。我仍在学习。 :)以为我只需要一个'='来表示实数(整数)和双'=='来表示'strings'之类的东西。谢谢! – 2014-12-01 18:52:56

+0

@JesseSzypulski欢迎您!祝你有美好的一天:D – Rizier123 2014-12-01 18:53:24