Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get dateTime from html for Countdown timer

I’m trying to get a dynamic date from a span with the id datetime and use that date for a countdown timer. But I see Nan all the time

<span id="datetime">30.11.2022 08:50:00</span>
<p id="demo"></p>

<script>
var enddateTime = document.getElementById('datetime').textContent;
// Set the date we're counting down to
var countDownDate = new Date(enddateTime).getTime();

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

  // Get today's date and time
  var now = new Date().getTime();

  // Find the distance between now and the count down date
  var distance = countDownDate - 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("demo").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("demo").innerHTML = "EXPIRED";
  }
}, 1000);
</script>

I tried using .textContent to get the field value
var enddateTime = document.getElementById('datetime').textContent;

Everything is fine in the console, but when I use in the timer script, I get NaN

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

const newDate = new Date('30.11.2022 08:50:00');

console.log(newDate); // Invalid Date

Your date format is simply invalid. Try for example using ‘2022-11-30 08:50:00’ as your date.

<span id="datetime">2022-11-30 08:50:00</span>

More here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading