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
CodePudding user response:
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.
CodePudding user response:
<span id="datetime">30.11.2022 08:50:00</span>
This value inside HTML element is invalid format date in Js. You should change the value to 2022-11-30 08:50:00. This is YYYY-MM-DD HH:mm:ss Date format in js.