1
votes

I have a need to get the difference between two dates in PHP, down to the millisecond. The dates are both DateTime objects (or compatible variants). Since PHP 7.2, DateTime stores milliseconds as well.

DateTime::diff() returns a DateInterval object, however, it doesn't differentiate between different length years or months:

  • "2019-01-01" — "2020-01-01" = 1 year (365 days)
  • "2020-01-01" — "2021-01-01" = 1 year (366 days)
  • "2019-01-01" — "2019-02-01" = 1 month (31 days)
  • "2019-02-01" — "2019-03-01" = 1 month (28 days)

Is there a nice built-in I haven't found yet that can do this, or will I have to roll my own function?

1
“however, it doesn't differentiate between different length years or months” - it’s not supposed to, it uses these “units” as a human would - from the first of one month to the first of the next is considered one month, no matter whether you are dealing with 30, 31 or just 28 days here. If you want something that handles this differently, you’ll need to write it yourself, whether milliseconds are involved or not. - misorude
So what is the output that you want ? give us an example - Accountant م
@misorude I never said it wasn't supposed to, just that that's not what I want. I would have thought a "scientific" version of DateTime::diff() might hav already been written. - CJ Dennis

1 Answers

2
votes

If you use DateTime::diff() to get the DateInterval, it will have a days property that will be set correctly. You can combine this with the h, i, s, and f properties to get the correct number of milliseconds.