2012-08-08 53 views
0

我已经浏览了网站上的问题,我认为我遇到的问题更深入一点。 我试过使用difftime()函数,但它对我来说结果为0。试图计算使用(当前php日期 - mySQL时间戳=天差异)

到目前为止,这是我做了什么

$currentDate = time(); 
//echo $printDate; 
//echo $currentDate; 
$editedDate = date("Y-m-d ", strtotime($printDate)); 
$editedCurrentTime = date("Y-m-d ", $currentDate); 


echo "$editedDate </br>"; 
echo "$editedCurrentTime </br>"; 

$timeDiff = ($editedCurrentTime - $editedDate); 
echo "$timeDiff </br>"; 
$numberDays = floor($timeDiff/(60*60*24)); 

我先保存时间();到currentDate中,printDate具有条目放入数据库的日期。两者都格式化,回声打印正确,就像它应该。第三个回声是由于某种原因减法变为0的地方。当我尝试一个strtotime($ currentDate)时,editedCurrentTime的回声变为1970-01-01。我猜这是一个小问题,与他们有不同格式的事实有关,但它仍然困扰着我。任何帮助将大大升值。

下面是输出的一个片段:

2012-08-01 
2012-08-08 
0 
2012-08-01 
2012-08-08 
0 
2012-08-01 
2012-08-08 
0 
2012-08-02 
2012-08-08 
0 

回答

2

date()函数返回基于你把它格式的字符串。您不能对字符串执行算术运算。

你应该做的是,首先计算时间戳(整数)的差异,你从数据库中检索time(),然后才格式化与date()功能这种差异。

(注:你应该存储日期和时间在Unix纪元整数格式的数据库了。)

+0

嘿,所以我试过了从时间戳中减去时间()的方法,但是它也返回错误的结果,差异仅仅是当前日期,计算后的$ numberDays仍然为0。 – user1058359 2012-08-08 14:01:26

+0

如果'$ printDate'已经是时间戳了,试试'$ foo = time() - $ printDate'。如果不是,则需要先将其转换为时间戳。数据最初是否存储在数据库中? – Whisperity 2012-08-08 14:03:23

+0

$ printDate直接从数据库中取出,哪一部分需要转换为时间戳? – user1058359 2012-08-08 14:11:53

相关问题