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

时间:2012-02-18 05:21:19

标签: php jquery mysql ajax time

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

我有这个设置:

<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我应该看到剩下的时间时:

<div id="time">5h:50min<div>

我在30分钟内再次发誓我看到

<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

}

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

任何想法?

感谢

2 个答案:

答案 0 :(得分:2)

使用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

答案 1 :(得分:1)

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

所以对你的例子来说:

$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 />";

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

演示:

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>​