PHP date_diff function broken?

谁都会走 提交于 2019-12-12 03:57:39

问题


Consider these two dates 2017/4/14, 2017/6/3

Using date_diff in php gives me this

  object(DateInterval)[6]
  public 'y' => int 0
  public 'm' => int 1
  public 'd' => int 20
  public 'h' => int 0
  public 'i' => int 0
  public 's' => int 0
  public 'weekday' => int 0
  public 'weekday_behavior' => int 0
  public 'first_last_day_of' => int 0
  public 'invert' => int 0
  public 'days' => int 50
  public 'special_type' => int 0
  public 'special_amount' => int 0
  public 'have_weekday_relative' => int 0
  public 'have_special_relative' => int 0

I have a task of creating a replicate of this function (as a assignment). But when I run these dates through my algorithm I get

object(stdClass)[4]
  public 'years' => int 0
  public 'months' => int 1
  public 'days' => int 19
  public 'total_days' => int 50
  public 'invert' => int 0 

And when I calculate the number of days by hand (manually) I still see this as 19 extra days. I am not looking for the assignment solution. But maybe some algorithm or maybe the date_diff function has some bugs I am not aware of?

For 200+ test cases my algorithm works, for 7 others it does not and it's always a day difference between my solution and php solution.


回答1:


Keep in mind that a month is not a fixed number of days, so it's going to depend which you gobble up into that "1 month."

If you start from 2017/4/14 and take full months first you'll get:

  • 4/14 -> 5/14: 1 month (30 days)
  • 5/14 -> 6/3: 20 days

While if you start from 2017/6/3 and work your way backward you'll get:

  • 6/3 -> 5/3: 1 month (31 days)
  • 5/3 -> 4/14: 19 days

So it's going to depend on the method you're using.

In short date_diff isn't broken here, and arguably your algorithm isn't either - dates are just funky things to work with.



来源:https://stackoverflow.com/questions/42332227/php-date-diff-function-broken

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!