如何用php和mysql计算剩余的剩余时间?
我有一种情况,我需要计算每6小时的剩余时间,每当我查看时间。如何用php和mysql计算剩余的剩余时间?
我有这样的设置:
<div id="time"><div>
<button>trigger</button>
更精确地说,我有一个触发器,得到一次首发:
$(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
我应该看到左tim E:
<div id="time">5h:50min<div>
我在30分钟内再次vizit我看到
<div id="time">5h:20min<div>
等。
问题是没有使用ajax或其他东西来回发送时间,而是发送正确的时间。
我在想什么是每次访问页面时发送的时间。第一次将其存储在表中的字段和其他时间将它们存储在一个单独的表场
id time1 time2
1 123456.. 123124..
的time1
保持未修改的,因为它是原来的时间和每一次我访问该页面时我送新的当前时间并更新time2
这里我有点失落。
这是我如何得到time1
:$getTime = $data->getTime($userId);
而且这件事是在每次时间:$time
我也知道,6H是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}<br />";
第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
<span id="countdown"></span>
这可能就是这种情况,我相信我认为这一个,让我试试看,如果它工作不正常让你知道 – Patrioticcow 2012-02-18 05:50:18
嗯,时间似乎并没有改变。我在数据库中插入时间,我可以看到剩下的时间是5小时:59分钟,但它停留在那里。 – Patrioticcow 2012-02-18 06:05:41
你想要一个恒定的倒数? – 2012-02-18 06:07:07
使用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
只是为了澄清,你问如何计算时间的剩余量? – 2012-02-18 05:29:29
是的请,我不知道为什么我使它如此复杂:) – Patrioticcow 2012-02-18 05:34:26
让我知道下面是你想要的... – 2012-02-18 05:37:48