我有两个时间戳由time()提供,并作为varchar存储在数据库中。
现在我要计算两次之间的差异;一个是1366627990
,另一个是$time2=time();
。
我使用了一个脚本
function dateDiff($time1, $time2, $precision = 3) {
date_default_timezone_set("UTC");
// If not numeric then convert texts to unix timestamps
if (!is_int($time1)) {
$time1 = strtotime($time1);
}
if (!is_int($time2)) {
$time2 = strtotime($time2);
}
// If time1 is bigger than time2
// Then swap time1 and time2
if ($time1 > $time2) {
$ttime = $time1;
$time1 = $time2;
$time2 = $ttime;
}
// Set up intervals and diffs arrays
$intervals = array('year','month','day','hour','minute','second');
$diffs = array();
// Loop thru all intervals
foreach ($intervals as $interval) {
// Set default diff to 0
$diffs[$interval] = 0;
// Create temp time from time1 and interval
$ttime = strtotime("+1 " . $interval, $time1);
// Loop until temp time is smaller than time2
while ($time2 >= $ttime) {
$time1 = $ttime;
$diffs[$interval]++;
// Create new temp time from time1 and interval
$ttime = strtotime("+1 " . $interval, $time1);
}
}
$count = 0;
$times = array();
// Loop thru all diffs
foreach ($diffs as $interval => $value) {
// Break if we have needed precission
if ($count >= $precision) {
break;
}
// Add value and interval
// if value is bigger than 0
if ($value > 0) {
// Add s if value is not 1
if ($value != 1) {
$interval .= "s";
}
// Add value and interval to times array
$times[] = $value . " " . $interval;
$count++;
}
}
// Return string with times
return implode(", ", $times);
}
我将该函数称为
echo dateDiff("1366627990",$time2, 3);
但是它给了我
43 years, 3 months, 22 days
虽然时间不应超过10 days
的最大值。
我的剧本有问题吗?
答案 0 :(得分:3)
好吧,首先抓住两个时间戳的intval(),从另一个中减去一个并取结果的绝对值。你最终会得到两次之间的总秒数。
然后使用其中一个示例将该数字(秒)转换为人类可读的内容:
答案 1 :(得分:2)
首先,不要指望差异小于10天。这是31年:
echo date("r", 366627990); // your first time. Fri, 14 Aug 1981 09:06:30 +0000
echo date("r", 1366971706); // $time2 in my case. Fri, 26 Apr 2013 10:21:46 +0000
好的,现在您已将日期更正为1366627990
。这是4天的差异:
echo date("r", 1366627990); // updated time. Mon, 22 Apr 2013 10:53:10 +0000
但是这个答案中提供的解决方案仍然是正确的,并且适用于您的新旧时间戳(以及任何其他两个时间戳:-))。
现在让我在您的脚本中解决问题,然后向您展示更好的计算时间和日期差异的替代方案。
问题是您的“如果不是数字然后将文本转换为unix时间戳”,请在开头查看。因为如果将UNIX时间戳作为字符串传递,这将无效,您显然会这样做。修复此问题的黑客将在函数的开头包含以下内容:
function dateDiff($time1, $time2, $precision = 3) {
// hack for passing timestamps as strings
if ($time1 == intval($time1)) {
$time1 = intval($time1);
}
if ($time2 == intval($time2)) {
$time2 = intval($time2);
}
现在,您的函数会产生正确的输出:
31 years, 8 months, 12 days
从版本5.2.0开始,PHP具有超级整洁DateTime
class和a diff method,这正是您所需要的:
$d1 = new DateTime();
$d1->SetTimestamp($time1);
$d2 = new DateTime();
$diff = $d1->diff($d2);
echo $diff->format("%y years, %m months, %d days");
这个也给你了
31 years, 8 months, 12 days
答案 2 :(得分:0)
尝试
<?php
$time1 = (int)1366971673; //The value of time() when I wrote this.
$time2 = (int)1366627990; //Your time value to compare.
$diff = (int)$time1-$time2;
echo round(($diff/60/60/24)).' days between dates.';
?>
应输出;
4 days between dates.