1

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.

1
  • 1
    Making an AJAX request every second for this is a rather bad solution to begin with. Such a countdown (or -up) should happen purely on the client side. Commented May 18, 2020 at 12:32

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.