获取 PHP 中两个日期之间的确切差异的简单方法,包括毫秒

Easy way to get the exact difference between two dates in PHP, including milliseconds

我需要获取 PHP 中两个日期之间的差异,精确到毫秒。日期都是 DateTime 对象(或兼容变体)。由于 PHP 7.2,DateTime 也存储毫秒。

DateTime::diff() returns一个DateInterval对象,但是,它不区分不同长度的年或月:

是否有我尚未找到的可以执行此操作的不错的内置函数,或者我是否必须推出自己的函数?

如果您使用 DateTime::diff() 获得 DateInterval,它将有一个 days 属性 将被正确设置。您可以将其与 hisf 属性结合使用以获得正确的毫秒数。