新搭建的Wordpress网站想要在页脚加上一个网站已运行时间的文字
在页脚(footer.php)添加以下代码
<?php date_default_timezone_set('Asia/Shanghai'); function Sec2Time($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); return (array) $value; }else{ return (bool) FALSE; } } // 本站创建的时间 $site_create_time = strtotime('2017-03-26 11:40:00'); $time = time() - $site_create_time; $uptime = Sec2Time($time); ?> 本站运行:<a><?php echo $uptime['years']; ?>年<?php echo $uptime['days']; ?>天<?php echo $uptime['hours']; ?>小时<?php echo $uptime['minutes']; ?>分<?php echo $uptime['seconds']; ?>秒 </a>
但此方式时间不会动态变化,于是采用Js实现:
<script language=javascript> function siteTime(){ window.setTimeout("siteTime()", 1000); var seconds = 1000 var minutes = seconds * 60 var hours = minutes * 60 var days = hours * 24 var years = days * 365 var today = new Date() var todayYear = today.getFullYear() var todayMonth = today.getMonth() var todayDate = today.getDate() var todayHour = today.getHours() var todayMinute = today.getMinutes() var todaySecond = today.getSeconds() /* Date.UTC() -- 返回date对象距世界标准时间(UTC)1970年1月1日午夜之间的毫秒数(时间戳) year - 作为date对象的年份,为4位年份值 month - 0-11之间的整数,做为date对象的月份 day - 1-31之间的整数,做为date对象的天数 hours - 0(午夜24点)-23之间的整数,做为date对象的小时数 minutes - 0-59之间的整数,做为date对象的分钟数 seconds - 0-59之间的整数,做为date对象的秒数 microseconds - 0-999之间的整数,做为date对象的毫秒数 */ var t1 = Date.UTC(2014,0,14,11,19,00) var t2 = Date.UTC(todayYear,todayMonth,todayDate,todayHour,todayMinute,todaySecond) var diff = t2-t1 var diffYears = Math.floor(diff/years) var diffDays = Math.floor((diff/days)-diffYears*365) var diffHours = Math.floor((diff-(diffYears*365+diffDays)*days)/hours) var diffMinutes = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours)/minutes) var diffSeconds = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours-diffMinutes*minutes)/seconds) document.getElementById("sitetime").innerHTML=" 已运行"+diffYears+" 年 "+diffDays+" 天 "+diffHours+" 小时 "+diffMinutes+" 分钟 "+diffSeconds+" 秒" } siteTime() </script> <a id="sitetime"></a>