简体   繁体   中英

How to make a countup timer instead of a countdown timer? (PHP, JQUERY AJAX)

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('Ymd H:i:s')); but it didn't work.

Many thanks in advance.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM