PHP,Javascript实时时钟:如何正确显示数据库上次更新的时间


PHP, Javascript live clock: how to correctly display last time database was updated?

尝试显示数据库上次更新的时间(实时和计数):

function show_clock(){
my_element = document.getElementById("js_clock")
var tt = new Date().getTime();
var my_date = new Date(<?php echo $latest_timestamp*1000; ?>);
var hours = my_date.getHours()
var minutes = my_date.getMinutes()
var seconds = my_date.getSeconds()
console.log(my_date);
console.log(hours);
console.log(minutes);
console.log(seconds);
var dn="PM"
if (hours<12)
        dn="AM"
if (hours>12)
        hours=hours-12
if (hours==0)
        hours=12
if (minutes<=9)
        minutes="0"+minutes
if (seconds<=9)
        seconds="0"+seconds
var ctime=hours+":"+minutes+":"+seconds+" "+dn
my_element.innerHTML="<b style='font-size:14;color:black;'>"+ctime+"</b>"
setTimeout("show_clock()",1000)
}
window.onload=show_clock

至于php:

$result = $newsfeed_db->queryDB($query);
foreach($result as $timestamp)
{
$latest_timestamp = $timestamp["db_date"];
}
$time_of_update = date("m/d/Y h:i", $latest_timestamp);
$tslu = (time() - $latest_timestamp);

显示器:

<div class="display_last_update"><?php echo "Database Last Updated: " . $time_of_update; ?></div>
<div class="display_last_update"><?php echo "Time Since Last Update: " . date("H", $tslu)." hours and ".date("i", $tslu)." minutes"; ?></div>
<div id="js_clock"><?php echo "Live Time Since Last Update: "; ?></div>

我在js控制台中的当前输出是

上次更新数据库的日期。它显示为:

2013年6月26日星期三14:29:35 GMT-0700(太平洋夏令时)

然后是该时间的小时分和秒。

现在,这4个日志也每隔一秒重复一次(基于1000的setTimeout)。所以,我觉得我走在了正确的轨道上,但还没有完全实现。

欢迎提出任何建议。

刚刚发现这个:

它将类似于这个代码:

$to_time = strtotime("2008-12-13 10:42:00");
$from_time = strtotime("2008-12-13 10:21:00");
echo round(abs($to_time - $from_time) / 60,2). " minute";
function dhm(t) {
    var cd = 24 * 60 * 60 * 1000,
    ch = 60 * 60 * 1000,
    d = Math.floor( t / cd),
    h = '0' + Math.floor( (t - d * cd) / ch),
    m = '0' + Math.round( (t - d * cd - h * ch) / 60000);
    return ["Time Since Last Update: " + d + " days", h.substr(-2) + " hours", m.substr(-2) + " minutes"].join(' ');
    }
    var last_update = new Date(<?php echo $latest_timestamp*1000; ?>);
            var interval = setInterval(function() {
            var now = new Date();
            var t = now.getTime() - last_update.getTime();
            document.getElementById("js_clock").innerHTML = dhm(t);
    }, 1000);

这是可以整理的,但可以按预期工作。