用PHP计算日期/时间之间的差异
问题描述:
我有一个Date对象(来自Pear),并且想要减去另一个Date对象以获得以秒为单位的时间差。用PHP计算日期/时间之间的差异
我已经尝试了一些东西,但第一次只给了我几天的差异,第二次将允许我将一个固定时间转换为unix时间戳而不是Date对象。
$now = new Date();
$tzone = new Date_TimeZone($timezone);
$now->convertTZ($tzone);
$start = strtotime($now);
$eob = strtotime("2009/07/02 17:00"); // Always today at 17:00
$timediff = $eob - $start;
**注**它总是小于24小时的差异。
答
了还是有点错误的价值观,但考虑到我有一个旧版本的PEAR日期的身边,也许它为你工作或为您提供关于如何解决:)
的提示<pre>
<?php
require "Date.php";
$now = new Date();
$target = new Date("2009-07-02 15:00:00");
//Bring target to current timezone to compare. (From Hawaii to GMT)
$target->setTZByID("US/Hawaii");
$target->convertTZByID("America/Sao_Paulo");
$diff = new Date_Span($target,$now);
echo "Now (localtime): {$now->format("%Y-%m-%d %H:%M:%S")} \n\n";
echo "Target (localtime): {$target->format("%Y-%m-%d %H:%M:%S")} \n\n";
echo $diff->format("Diff: %g seconds => %C");
?>
</pre>
答
您确定Pear Date对象的转换 - >字符串 - >时间戳可以可靠地工作吗?这就是正在这里进行:
$start = strtotime($now);
作为替代方案,你可以根据documentation
$start = $now->getTime();
答
要做到这一点,而不梨,找到秒钟,直到” 17得到这样的时间戳: 00你可以这样做:
$current_time = mktime();
$target_time = strtotime (date ('Y-m-d'. ' 17:00:00'));
$timediff = $target_time - $current_time;
没有测试过它,但它应该做你所需要的。
答
我不认为你应该将整个Date对象传递给strtotime。改用其中之一;
$start = strtotime($now->getDate());
或
$start = $now->getTime();
答
也许有些人想用facebook的方式有时差。它告诉你“一分钟前”或“2天前”等...这里是我的代码:
function getTimeDifferenceToNowString($timeToCompare) {
// get current time
$currentTime = new Date();
$currentTimeInSeconds = strtotime($currentTime);
$timeToCompareInSeconds = strtotime($timeToCompare);
// get delta between $time and $currentTime
$delta = $currentTimeInSeconds - $timeToCompareInSeconds;
// if delta is more than 7 days print the date
if ($delta > 60 * 60 * 24 *7) {
return $timeToCompare;
}
// if delta is more than 24 hours print in days
else if ($delta > 60 * 60 *24) {
$days = $delta/(60*60 *24);
return $days . " days ago";
}
// if delta is more than 60 minutes, print in hours
else if ($delta > 60 * 60){
$hours = $delta/(60*60);
return $hours . " hours ago";
}
// if delta is more than 60 seconds print in minutes
else if ($delta > 60) {
$minutes = $delta/60;
return $minutes . " minutes ago";
}
// actually for now: if it is less or equal to 60 seconds, just say it is a minute
return "one minute ago";
}
$的输出格式现在是否与输入到strtotime()中的字符串相同?即“yyyy/mm/dd H:i” – Mathew 2009-07-02 13:28:59