为什么datetime-> days总是返回正数 [英] Why does datetime->days always returns a positive number

查看:75
本文介绍了为什么datetime-> days总是返回正数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

// Difference from a date in the future:
$a = new DateTime('2000-01-01');
$b = new DateTime('2000-01-05');
$interval = $b->diff($a);
return $interval->days;             // Returns 4


// Difference from a date in the past:
$a = new DateTime('2000-01-01');
$b = new DateTime('1999-12-28');
$interval = $a->diff($b);           // Arguments swapped
return $interval->days;             // Returns 4

为什么这两个函数都返回正数4?
如果日期是过去日期,如何返回负数?

Why do both of these functions return positive 4? How do I return a negative number if a date is in the past?

推荐答案

您可以使用 DateInterval :: format

You could use DateInterval::format.

返回$ interval-> format(%r%a);

根据需要转换为int:

Cast to int if needed:

返回(int)$ interval-> format(%r%a);

这篇关于为什么datetime-> days总是返回正数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆