改爲使用DateTime來嘗試。
這需要一些變通方法,因爲DateInterval
(由DateTime::diff()
返回)不計算微秒,所以你需要這種手工
$pageTime = new DateTime("2012-04-23T16:08:14.1 - 5 hours");
$rowTime = new DateTime("2012-04-23T16:08:16.9 - 5 hours");
// the difference through one million to get micro seconds
$uDiff = abs($pageTime->format('u')-$rowTime->format('u'))/(1000 * 1000);
$diff = $pageTime->diff($rowTime);
echo $diff->format('%s')-$uDiff;
我總是建議DateTime
由於其靈活性,你應該看看它
編輯
爲了向後保持兼容於PHP 5.2也採用相同的方法爲f或毫秒:
$pageTime = new DateTime("2012-04-23T16:08:14.1 - 5 hours");
$rowTime = new DateTime("2012-04-23T16:08:16.9 - 5 hours");
// the difference through one million to get micro seconds
$uDiff = abs($pageTime->format('u')-$rowTime->format('u'))/(1000 * 1000);
$pageTimeSeconds = $pageTime->format('s');
$rowTimeSeconds = $rowTime->format('s');
if ($pageTimeSeconds + $rowTimeSeconds > 60) {
$sDiff = ($rowTimeSeconds + $pageTimeSeconds)-60;
} else {
$sDiff = $pageTimeSeconds - $rowTimeSeconds;
}
if ($sDiff < 0) {
echo abs($sDiff) + $uDiff;
} else {
// for the edge(?) case if $dt2 was smaller than $dt
echo abs($sDiff - $uDiff);
}
darn ...這看起來很有希望,但它需要5.3+,我在5.2,我無法控制升級:(儘管 – slinkhi 2012-04-23 22:43:22
是因爲DateTime :: diff()'。這意味着你會需要手動做這個減法,看看我的編輯:)。 – 2012-04-23 22:50:35
我看...一般來說,這看起來像它幫助提取數據更容易(而不是使用正則表達式),但我認爲你的數學/邏輯是關閉的。例如,如果我有'$ pageTime = new DateTime(「2012-04-23T16:08:14.662-05:00」); $ rowTime = new DateTime(「2012-04-23T16:08:19.954-05:00」);'我應該得到'5.292',但它正在輸出'4.708'。此外,您的代碼僅處理秒和微秒之間的時間差異。如果你以'2012-04-23T16:08:59.9-05:00'開始並以'2012-04-23T16:09:00.1-05:00'結束,你應該得到'0.2',但是你的代碼會給我'58.2' ..(續) – slinkhi 2012-04-23 23:38:28