Reputation: 109
I made a countdowntimer in PHP and jQuery AJAX who is showing every second the variable named $timeleft.
timer.js
$(function()
{
var timertext = $("[timer]");
setInterval(function()
{
$.post("timer.php", {type : "timerupdate"}, function(data)
{
timertext.html("Time left: " + data + " seconds")
});
}, 1000);
});
timer.php
date_default_timezone_set("Europe/Amsterdam");
$timecountdownend = strtotime("2020-05-18 14:30:00");
$timecountdownstart = strtotime("now");
$startdatetime = "2020-05-18 14:07:00"; //variable for starting datetime
if(date('Y-m-d H:i:s') >= $startdatetime){
$timeleft = $timecountdownend - $timecountdownstart;
if(isset($_POST["type"]) === true && $_POST["type"] == "timerupdate")
{
echo ($timeleft);
}
}
Explained: a timer that starts when it's a specific time ($startdatetime) and counting the seconds till the $timecountdownend time. It's working fine, but I actually want to count up the second instead of counting down. So that it start counting with 1 second if $startdatetime has reached and every second is counting up till the $timecountdownend has reached. How can I do this with strtotime? I've tried many things like $timeleft = $timecountdownend - strtotime(date('Y-m-d H:i:s')); but it didn't work.
Many thanks in advance.
Upvotes: 1
Views: 1562
Reputation: 431
First if You have timeleft its Your counter : -2820 You can simply multiple it by (-1) : -2820 * (-1) = 2820
date_default_timezone_set("Europe/Amsterdam");
$timecountdownend = strtotime("2020-05-18 14:30:00");
$timecountdownstart = strtotime("now");
$startdatetime = "2020-05-18 14:07:00"; //variable for starting datetime
$timeleft = $timecountdownend - $timecountdownstart;
echo ($timeleft);
echo(PHP_EOL);
echo ($timeleft*(-1));
echo(PHP_EOL);
echo( date('Y-m-d h:i:sa',strtotime($startdatetime)+$timeleft*(-1)));
http://sandbox.onlinephpfunctions.com/code/792ec42255d85a45c377b6e8d34cbde143430824
Upvotes: 2