dqw7121 2017-02-19 20:03
浏览 90

PHP date_diff函数坏了吗?

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条回答 默认 最新

  • douduan7295 2017-02-20 01:57
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路