PHP commodity seconds kill timing implementation code

  • 2020-03-31 20:41:57
  • OfStack

The requirement should have hour minute second real-time countdown display, the user side changes the date time will not affect the normal display of the countdown (that is, the server time).

In fact, this is the same requirement as the time limit function of many exams and other systems.

You can't use ajax to get server time every second, so real-time countdown must be done in javascript. It's easy. There are tons of examples on the Internet.

Now the problem is to fix the effect of the date and time of the client changes on our display.

The solution is to calculate the time difference between the client and the server, and the problem is solved.

This way, you only need to run PHP once, and the real-time countdown time is synchronized with the server's time.

The theory is synchronous, but the actual test will have an error of 1 second. (the specific reason is related to the network speed, the faster the network speed, the smaller the error), but this will never affect our requirements above.

Note: the time of seckill is from 0:00 to 10:00pm.

Code is as follows:
 
<?php 

//PHP time is in seconds. Js time is in milliseconds

date_default_timezone_set('PRC'); 
//date_default_timezone_set("Asia/Hong_Kong");// region  

//Configure daily activity periods
$starttimestr = "08:00:00"; 
$endtimestr = "22:00:00"; 

$starttime = strtotime($starttimestr); 
$endtime = strtotime($endtimestr); 
$nowtime = time(); 
if ($nowtime<$starttime){ 
die(" The campaign hasn't started yet , The activity time is: {$starttimestr} to {$endtimestr}"); 
} 
$lefttime = $endtime-$nowtime; //Actual time remaining (seconds)
?> 

<script language="JavaScript"> 
<!-- // 
var runtimes = 0; 
function GetRTime(){ 
var nMS = <?=$lefttime?>*1000-runtimes*1000; 
var nH=Math.floor(nMS/(1000*60*60))%24; 
var nM=Math.floor(nMS/(1000*60)) % 60; 
var nS=Math.floor(nMS/1000) % 60; 
document.getElementById("RemainH").innerHTML=nH; 
document.getElementById("RemainM").innerHTML=nM; 
document.getElementById("RemainS").innerHTML=nS; 
if(nMS>5*59*1000&&nMS<=5*60*1000) 
{ 
alert(" Five minutes left! "); 
} 
runtimes++; 
setTimeout("GetRTime()",1000); 
} 
window.onload=GetRTime; 
// --> 
</script> 

<h4><strong id="RemainH">XX</strong>:<strong id="RemainM">XX</strong>:<strong id="RemainS">XX</strong></h4> 

Related articles: