每當用戶執行特殊操作時,我都得到了一個腳本,它保存了一個時間戳(使用time()函數)。從用戶可讀格式返回從時間戳到現在的時間差
我想在一個頁面上顯示多久以前用戶以易於閱讀的用戶方式執行此操作。目前,我得到它顯示有多少個小時前,它大約是的,但我想它在某種程度上看起來像這樣返回:
1天,5小時30 mintues方式...
每當用戶執行特殊操作時,我都得到了一個腳本,它保存了一個時間戳(使用time()函數)。從用戶可讀格式返回從時間戳到現在的時間差
我想在一個頁面上顯示多久以前用戶以易於閱讀的用戶方式執行此操作。目前,我得到它顯示有多少個小時前,它大約是的,但我想它在某種程度上看起來像這樣返回:
1天,5小時30 mintues方式...
達到你想要什麼,你可以簡單地做
$target = strtotime("Feb 7 2013 2:15 AM");
$now = time();
$diff = $now - $target;
$days = floor(($diff)/24/60/60);
$hours = floor(fmod($diff, 24*60*60)/60/60);
$minutes = floor(fmod(fmod($diff, 24*60*60),60*60)/60);
echo $days . " days " . $hours . " hours " . $minutes . " minutes"; // e.g. "2 days 14 hours 54 minutes"
一個更通用的解決方案
function timeago($timestamp) {
// Predefine variables
$timeago = '';
$past = FALSE;
$future = FALSE;
$prefixAgo = NULL;
$prefixFromNow = NULL;
$suffixAgo = "ago";
$suffixFromNow = "from now";
$wordSeperator = " ";
// Current time
$current = time();
// Seconds ago
$seconds = abs($current - $timestamp);
// Determine whether the time is in the future or the past
if ($current >= $timestamp) {
$past = TRUE;
} else {
$future = TRUE;
}
// Calculate time ago in different formats
$minutes = $seconds/60;
$hours = $minutes/60;
$days = $hours/24;
$months = $days/30;
$years = $days/365;
// Format time ago according to calculated time
if ($seconds < 45) { $timeago = "less than a minute"; }
else if ($seconds < 90) { $timeago = "about a minute"; }
else if ($minutes < 45) { $timeago = round($minutes) . " minutes"; }
else if ($minutes < 90) { $timeago = "about an hour"; }
else if ($hours < 24) { $timeago = "about " . round($hours) . " hours"; }
else if ($hours < 42) { $timeago = "a day"; }
else if ($days < 30) { $timeago = round($days) . " days"; }
else if ($days < 45) { $timeago = "about a month"; }
else if ($days < 365) { $timeago = round($months) . " months"; }
else if ($years < 1.5) { $timeago = "about a year"; }
else { $timeago = round($years) . " years"; }
// Append prefix and suffix
if (!empty($prefixAgo)) { $prefixAgo = $prefixAgo . $wordSeperator; }
if (!empty($suffixAgo)) { $suffixAgo = $wordSeperator . $suffixAgo; }
if (!empty($prefixFromNow)) { $prefixFromNow = $prefixFromNow . $wordSeperator; }
if (!empty($suffixFromNow)) { $suffixFromNow = $wordSeperator . $suffixFromNow; }
if ($past) { $timeago = $prefixAgo . $timeago . $suffixAgo; }
if ($future) { $timeago = $prefixFromNow . $timeago . $suffixFromNow; }
// Return results
if (!empty($timeago)) {
return $timeago;
} else {
return NULL;
}
}
echo date('Y-m-d', time());
顯示2013-02-09
您還可以看到manual,date('Ymd H:i:s',time());將輸出2013年2月9日17時57分三十秒
一種讓它走的方法: 1天5小時30分鐘或類似的東西? – PeaceDealer 2013-02-09 16:57:27
嘗試:
$diff = date_diff($lastaccess, new DateTime(date('d-m-Y'));
echo $diff->format('Last access on: %s seconds %d days %m months and %y years ago')};
當前使用的是這樣的:'$ time =(time() - $ lines ['timestamp'])/ 3600;'然後'echo round($ time)' – PeaceDealer 2013-02-09 16:54:42