[英]Calculate the difference between date/times in PHP
我有一個Date對象(來自Pear)並且想要減去另一個Date對象以獲得以秒為單位的時間差。
我嘗試了一些東西,但第一個只是給了我幾天的差異,第二個允許我將一個固定時間轉換為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對象 - > string - > timestamp的轉換是否可靠? 這就是在這里做的:
$start = strtotime($now);
作為替代方案,您可以根據文檔獲得這樣的時間戳
$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";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.