7

enter image description hereHi I have a JavaScript for countdown which is selecting time form MySQL and it is working fine on (Chrome, Firefox), but on (IE and Safari) it is returning "NaNd NaNh NaNm NaNs".

I have attached my code below.

<?php
$con = mysqli_connect("localhost", "root", "", "timer") or die("Error Could 
not connect to the database Sir." . mysqli_error($con));

$query = mysqli_query($con, "SELECT * FROM counter WHERE id = 1") or 
die(mysqli_error($con));
$row = mysqli_fetch_array($query)or die(mysqli_error($con));



?>
<div id="form<?php echo $row['id'];?>" style="color:green" class="form-
group">                      
</div>


<Script>
function createCountDown(elementId, date){
console.log(date);
// Set the date we're counting down to
var countDownDate = new Date(date).getTime();
console.log(countDownDate);

// Update the count down every 1 second
var x = setInterval(function(){

// Get todays date and time


var now = new Date().getTime();

// Find the distance between now an the count down date
var distance = (countDownDate) - (now);

//Hint on converting from object to the string.
//var distance = Date.parse(countDownDate) - Date.parse(now);

// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
//console.log(days);
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 *
                                                             60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);

// Display the result in the element with id="demo"
document.getElementById(elementId).innerHTML = days + "d " + hours + "h "
  + minutes + "m " + seconds + "s ";

// If the count down is finished, write some text
if (distance < 0)
{
  clearInterval(x);
  document.getElementById(elementId).innerHTML = "ORDER EXPIRED";
}
}, 1000);
}
createCountDown("form<?php echo $row['id'];?>", "<?php echo 
$row['time_to_expire'] ;?>")
</Script>

Please check if i am missing something again. thank you for all the replies.

5
  • try this createCountDown("form<?php echo $row['id'];?>", "<?php echo $row['time_to_expire'] ;?>") you are using single quote 'form<?php echo $row['id'];?>' Commented Sep 8, 2017 at 6:31
  • That is NOT a matter or quote use. I reproduced the issue. Commented Sep 8, 2017 at 6:33
  • Thank you for the replies but I have tried inserting the quote it doesn't work as @LouysPatriceBessette has mentioned. Commented Sep 8, 2017 at 6:37
  • 1
    @LouysPatriceBessette Still the quotes are not valid and have to be fixed. Commented Sep 8, 2017 at 6:38
  • Yes... I have to admit... It is about quote. Remove the quote around "<?php echo $row['time_to_expire'] ;?>" because that has to be an integer (will be passed to Date() an IE do not digest string on that. Issue fixed here But that wasn't a single/double combinaison issue. Commented Sep 8, 2017 at 6:38

3 Answers 3

2

EDIT

Internet Explorer and Safari aren't tolerant on malformed dates.

The date passed from PHP to JavaScript Date() : 2017-09-30 00:00:00 was "malformed". It came from PHP Date("Y-m-d H:i:s"); which is VERY commonly used...

The fix on JavaScript side is: date = date.replace(" ","T");

It also could be fixed on PHP side with: $date = Date("Y-m-d\TH:i:s");
Or if the date comes form a database:

$date = str_replace(" ","T",$row['time_to_expire']);
createCountDown("form<?php echo $row['id'];?>", "<?php $date;?>")

The resulting date string is then 2017-09-30T00:00:00, which is ISO 8601 compliant.

The issue was abvout ONE character!
I'll remember that one. ;)

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

10 Comments

If it isn't solving the issue... (I suddenly have a doubt) Please add console.log(date); right under function createCountDown(elementId, date){ and console.log(countDownDate); right under var countDownDate = new Date(date).getTime();.
Hi guys I have tried all the solutions that you have provided and they are still not working, i have tried to add as #LouysPatriceBessette and it doesn't make a different and i have tried #user2486 still the same and #yogesh patel doesn't work. please if there is anything i am missing tell me i have updated the post with my latest code. Thanks
Tell me what's the output of your console logs... As I asked previously. That will help me.
this is the output of my console 1506722400000
Chrome and FIrefox work but IE and Safari are returning this: NaNd NaNh NaNm NaNs
|
2

Check carefully ' single quotes here, Use double quotes for first parameter as second param.

createCountDown("form<?php echo $row['id'];?>", "<?php echo $row['time_to_expire'] ;?>")

Here is working example

function createCountDown(elementId, date) 
    {
    // Set the date we're counting down to
    var countDownDate = new Date(date).getTime();
    //console.log(countDownDate.getTime());
    // Update the count down every 1 second
    var x = setInterval(function() 
    {

      // Get todays date and time


      var now = new Date().getTime();

      // Find the distance between now an the count down date
      var distance = (countDownDate) - (now);

      //Hint on converting from object to the string.
      //var distance = Date.parse(countDownDate) - Date.parse(now);

      // Time calculations for days, hours, minutes and seconds
      var days = Math.floor(distance / (1000 * 60 * 60 * 24));
      var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 
      60));
      var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
      var seconds = Math.floor((distance % (1000 * 60)) / 1000);

      // Display the result in the element with id="demo"
      document.getElementById(elementId).innerHTML = days + "d " + hours + "h "
      + minutes + "m " + seconds + "s ";

      // If the count down is finished, write some text 
      if (distance < 0) 
      {
        clearInterval(x);
        document.getElementById(elementId).innerHTML = "ORDER EXPIRED";
      }
      }, 1000);
      }
      createCountDown('form1', "08-09-2017 12:10:00Z");
      createCountDown('form2', "08-09-2018 12:10:00Z");
<div id="form1"></div>
<div id="form2"></div>

1 Comment

Just to mention that even if this advise is good, the PHP is executed long before the JS, so in this case, there was absolutely no quote issue. ;)
2

Use moment.js and try below code for timer

    var eventTime = moment("target time").unix(),
                currentTime = moment().unix(),
                diffTime = eventTime - currentTime,
                duration = moment.duration(diffTime * 1000, "milliseconds"),
                interval = 1000;

            if (diffTime > 0) {
                var timer = setInterval(function () {
                    duration = moment.duration(duration.asMilliseconds() - interval, 'milliseconds');
                    var h = moment.duration(duration).hours(),
                        m = moment.duration(duration).minutes(),
                        s = moment.duration(duration).seconds();

                    // show how many hours, minutes and seconds are left
                    var temp = '<div><span>' + h + '</span> hr </div> <div><span>'
                        + m + '</span> min </div> <div><span>' + s +
                        '</span> sec </div>';
                    $(elementId).html(temp);

                   if ((h == 0 && m == 0 && s == 0) || (s < 0)) {
                      clearInterval(timer);

                }, interval);
            }
       }

5 Comments

The exit condition about "ORDER EXPIRED" and the clearInterval is badly missing in your suggestion. You could improve that. Moment is a good thing to use... But OP script can also be debugged.
As per your suggestion code for clearInterval added. If it helpful, you can give upvote. :)
You should test your solutions... There.s a missing } for the last if. That fixed, the console shows Deprecation warning: value provided is not in a recognized RFC2822 or ISO format..
@LouysPatriceBessette I have a problem with this solution again. after uploading to the server the timer is adding 24hrs if the the time if over 12hrs and if the time is below 12hrs the counter count in 4seconds not 1second
mmm Strange enought. You should post your actual code in a new question.

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.