如何用php和mysql计算剩余的剩余时间?

我有一种情况,每当我查看时间时,我需要每6个小时计算剩余时间。

我有这个设置:

更确切地说,我有一个启动时间的触发器:

 $(buttom).on('click', function(){ ..... send through ajax the current time to a php file ...if success, get the response and place it in the div }); 

在php文件中我将该时间存储到数据库中

 if (isset($_POST['time'])){ $storeTime->timestore($_POST['time']); } 

现在发生的是每当我看到div我应该看到剩余的时间:

 
5h:50min

我在30分钟内再次发现

 
5h:20min

等等。

问题不是使用ajax或其他东西来回发送时间,而是发送正确的时间。

我想的是每次访问页面时发送时间。 首次将其存储在表字段中,其他时间将它们存储在单独的表字段中

 id time1 time2 1 123456.. 123124.. 

time1保持不变,因为它是原始时间,每次我访问页面时,我发送新的当前时间并更新时间2

在这里,我有点失落。

这就是我得到time1$getTime = $data->getTime($userId);

这是每次都有的时间: $time

我也知道6小时是21600

所以

 if ( $time >= ($newTime + 21600) ){ //if the current time is bigger than the first time + 6h it means that 6h have passed // store the new time in the database for reference as the new main time } else { // 6h have not passed yet and we need to calculate how much time is left //here i get confuzed } 

我知道这篇文章可能有点混乱,但我希望它可以理解。

有任何想法吗?

谢谢

如果您要存储上次访问该网站的时间,则只需存储一次。

所以对你的例子:

 $current_time = time(); $last_visit_time = $data->getTime($userId); $since_last_visit_time = $current_time - $last_visit_time; $six_hours_in_seconds = 21600; if($since_last_visit_time > $six_hours_in_seconds) { // not sure of the function call here so using yours // store new time as it's been over 6 hours $storeTime->timestore($current_time); $remaining_time = $six_hours_in_seconds; } else { $remaining_time = $six_hours_in_seconds - $since_last_visit_time; } echo "Remaining Seconds: {$remaining_time}
";

第2部分使用JavaScript / Ajax,您可以使用它来显示重新生成时间

演示:

JS

 var time_in_seconds = 21600; // this would be the $remaining_time PHP variable setInterval(function() { $('#countdown').html(seconds2time(time_in_seconds)); time_in_seconds--; }, 1000); function seconds2time(seconds) { var hours = Math.floor(seconds / 3600); var minutes = Math.floor((seconds - (hours * 3600)) / 60); var seconds = seconds - (hours * 3600) - (minutes * 60); var time = ""; if (hours != 0) { time = hours+":"; } if (minutes != 0 || time !== "") { minutes = (minutes < 10 && time !== "") ? "0"+minutes : String(minutes); time += minutes+":"; } if (time === "") { time = seconds+"s"; } else { time += (seconds < 10) ? "0"+seconds : String(seconds); } return time; } 

HTML

  

使用TIME_TO_SEC(TIMEDIFF(final_time, initial_time))

 SELECT TIME_TO_SEC(TIMEDIFF('17:00:00', '09:00:00')) -- 28800 SELECT TIME_TO_SEC(TIMEDIFF('12:30:00', '12:00:00')) -- 1800 SELECT TIME_TO_SEC(TIMEDIFF('10:30:00', '10:15:00')) -- 900