1 后台定义接口
// 统计站点运行时间,格式 年 月 日 时 分 秒
public function getBuildTime()
{
    // 设置时区
    date_default_timezone_set('Asia/Shanghai');
    // 在下面按格式输入本站建立的时间
    $site_create_time = strtotime('2023-07-29 20:15:00');
    $time = time() - $site_create_time;
    if(is_numeric($time)){
        $value = array(
            "years" => 0, "days" => 0, "hours" => 0, "minutes" => 0, "seconds" => 0,
        );
        if($time >= 31556926){
            $value["years"] = floor($time/31556926);
            $time = ($time%31556926);
        }
        if($time >= 86400){
            $value["days"] = floor($time/86400);
            $time = ($time%86400);
        }
        if($time >= 3600){
            $value["hours"] = floor($time/3600);
            $time = ($time%3600);
        }
        if($time >= 60){
            $value["minutes"] = floor($time/60);
            $time = ($time%60);
        }
        $value["seconds"] = floor($time);
        $refresh_time = $value['years'].'年'.$value['days'].'天'.$value['hours'].'时'.$value['minutes'].'分'.$value['seconds'].'秒';
        return json(['code' => 1, 'msg' => '时间获取成功', 'time' => $refresh_time]);
    } else {
        return json(['code' => 0, 'msg' => '时间获取失败', 'time' => '']);
    }
}2 前台调用接口
<tr>
    <td>运行时间</td>
    // 页面显示时,先拿后台时间,然后再通过定时器实时更新时间
    <td id="refresh_time">{:getBuildTime()}</td>
</tr>
<script>
    function getRefreshTime()
    {
        var p = new Promise(function(resolve, reject){
            $.ajax({
                url: "{:url('home/Index/getBuildTime')}",
                method: 'GET'
            }).then(({code, msg, time}) => {
                if (code === 1) {
                    // 正常情况
                    resolve(time);
                } else {
                    // 异常情况
                    reject('时间异常');
                }
            })
        });
        p.then(function(data){
            $('#refresh_time').text(data);
        },function(info){
            $('#refresh_time').html(`<span style="color:red;">${info}</span>`);
        });
    }
    // 设置定时器
    setInterval(function(){
        getRefreshTime();
    }, 1000);
</script> 智享笔记
								    智享笔记								 
                             
                             
                            