我正在嘗試使倒數計時器從當前時間倒計時到將來的設定時間。我用JS完美地工作,但我需要使用服務器的當前時間而不是客戶端。使用曆元服務器時間的Javascript倒數計時器
我試圖通過使用PHP來獲取服務器時期,然後我想每秒增加它並轉換成一個Javascript日期對象,所以我可以做比較,並將剩餘時間寫入DOM。我不知道這是否可行,甚至是最好的方式,但目前它不會增加或從服務器提供有效/正確的日期。
<!DOCTYPE html>
<?php
$end_time = $_GET['time'];
$server_epoch = $_SERVER['REQUEST_TIME'];
?>
<html>
<head>
<script type="text/javascript">
var counter = setInterval(function(){
countdown(<?= $server_epoch ?>, "<?= $end_time?>");
server_e++;
}, 1000);
/*
* Calculates the time remaining to the nearest second from the current time until the
* end time and updates DOM elements with id of "time" to display the formatted time(D,H,M,S)
*/
function countdown(server, end_time){
var current_time = new Date(server);
var end = new Date(end_time);
var time_left = (end - current_time)/1000;
if(time_left <= 0){
document.getElementById("time").innerHTML= "Auction has ended" ;
} else {
var days = Math.floor(time_left/86400);
var hours = Math.floor(((time_left/86400)-days) * 24);
var mins = Math.floor(((((time_left/86400)-days) * 24)-hours)* 60);
var secs = Math.floor(((((((time_left/86400)-days) * 24)-hours)* 60)-mins) * 60);
var day_string = " days, ";
if (days == 1){
day_string = " day, "
}
document.getElementById("time").innerHTML= days + day_string + hours +" hours, " + mins +" mins, "+ secs+" secs" ;
document.getElementById("current").innerHTML= current_time ;
document.getElementById("ends").innerHTML= end ;
}
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<div id="time_box">
<form method="get" action="index.php">
<input type="text" name="time"/>
<input type="submit" value="submit">
</form>
php time: <?= $server_epoch; ?><br/>
Current time: <div id="current"></div> <br/>
Ends: <div id="ends"></div><br/>
Time left: <div id="time"></div>
</div>
</body>
</html>
你能通過一個在時間字段中發送的值的例子嗎? – hdvianna
[使用JavaScript倒計時服務器端時間]可能的重複(http://stackoverflow.com/questions/6755940/using-javascript-countdown-with-server-side-time) – murgatroid99