问题
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