1

I have some PHP script that echos how much time is left until an event. The time is outputted in a format that looks like 23h 15m 4s

Here is my PHP code:

    $now = new DateTime();
    $future_date = new DateTime($res['post_time']); # post_time is the time of event
    $interval = $future_date->diff($now);
    $time_until = rtrim(sprintf("%s%s%s",
        $interval->h > 0 ? $interval->h . "h " : "",
        $interval->i > 0 ? $interval->i . "m " : "",
        $interval->s > 0 ? $interval->s . "s " : ""
        )
    ); # Format time to not have '0'
   echo "Time until event " . $time_until;

Is there a way to have the time update every second in Javascript? I imagine that the echo will look something like

echo "Time until event <span id='countdown'>" . $time_until . "</span>";

where the JS will do something with #countdown?

Bijan
  • 7,737
  • 18
  • 89
  • 149
  • There are many ways to do it. You could use an ajax call every second to get the updated time, or you could echo the total number of seconds and then do the day/minute/second math via javascript, which would allow you to countdown/update the time every second. – Richard Theobald Jan 10 '16 at 02:12
  • 4
    Possible duplicate of [The simplest possible JavaScript countdown timer?](http://stackoverflow.com/questions/20618355/the-simplest-possible-javascript-countdown-timer) – Phiter Jan 10 '16 at 02:13
  • 4
    @RichardTheobald, `AJAX` will not be appropriate here..There will be latency in that approach.. – Rayon Jan 10 '16 at 02:13
  • @RayonDabre Good point. The time would likely no longer be accurate to the second if one chose to use ajax. Especially with a call every second. – Richard Theobald Jan 10 '16 at 02:15
  • @PhiterFernandes: Not quite that simple. My PHP script removes 0s so the time can be in format of `23h 47m 1s` or `1h 18s` for example – Bijan Jan 10 '16 at 02:18

2 Answers2

2

What you need to do is:

  • convert the received time from php to a variable. i would suggest and array like [ hour, minutes, seconds].
  • Use setInterval (functionExample, 1000).
  • In the setInterval function , you just decrease the seconds, minutes, and hours and update the span#countdown.

var time = "5h 10m",
    time_formatted = [0,0,0],
    time_array = time.split(' ');

time_array.forEach(function(element){
    var i = -1;
    if (element.indexOf('h') > -1){
        i = 0;   
    } else if (element.indexOf('m') > -1){
        i = 1;
    } else if (element.indexOf('s') > -1){
        i = 2;
    }

    if (i != -1)
     time_formatted[i] = parseInt(element.substring(0, element.length -1));

    });

console.log(time_formatted);

  • How would I store the time to a variable JS can read? The time can vary between formats like `23h 17m 4s` or `12h 9s` – Bijan Jan 10 '16 at 02:23
  • [Conversion code here](https://repl.it/BckG/2) Edit: tried to write the code here, but it did not format. –  Jan 10 '16 at 02:38
0

You must use the JS setInterval method