我试着取两个日期并相互减去它们
$now = date('2014-07-17');
$due = date('2014-07-20');
$diff = $now - $due;
$timeRemaining = floor($diff/(60*60*24);
每次都返回0而不是3
date()
接受字符串格式和Unix Timestamp作为参数,而不仅仅是文本日期字符串。所以对date()
的调用都返回原始值给你,因为它们都是无效参数。由于字符串的减法,类型杂耍为这两个变量返回2014
,然后结果是它们相等。
使用strtotime()
代替,它返回您期望的时间戳,并且可以使用它进行日期计算。
同样,如果你想要一个正整数作为结果,你需要把后面的日期放在前面。
$now = strtotime('2014-07-17');
$due = strtotime('2014-07-20');
$diff = $due - $now;
$timeRemaining = floor($diff/(60*60*24);
您正在减去两个字符串,它们将每个字符串的类型转换为整型值2014
,这当然会返回0
。
$now = (int) date('2014-07-17'); // Will make $now = 2014
这里有一种方法(但我建议使用DateTime
对象代替):
$now = strtotime('2014-07-17');
$due = strtotime('2014-07-20');
$diff = $due - $now; // Notice how you had your original equation backwards
$timeRemaining = floor($diff/(60*60*24));
下面是如何使用DateTime
对象:
$now = new DateTime('2014-07-17');
$due = new DateTime('2014-07-20');
$diff = $due->sub($now);
$timeRemaining = $diff->format('%d');
您需要使用strtotime
,而不是date
。你需要反转你的减法公式——较早的日期($now
)应该从未来的日期($due
)中减去。
$now = strtotime('2014-07-17');
$due = strtotime('2014-07-20');
$diff = $due - $now;
$timeRemaining = floor($diff/(60*60*24));
<<p> 看到演示/strong>