Reputation: 105
I made a countdown for my web page; it works fine all browser except Mozilla and IE.
What am I doing wrong and how can I resolve it?
Below is my code:
***var dt = '2018-06-14 11:59 AM';
var ids= 'Demo1';***
function getTimes(dt, ids) {
var countDownDate = new Date(dt).getTime();
var x = setInterval(function() {
var now = new Date().getTime();
var distance = countDownDate - now;
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);
var op = hours+":"+minutes+":"+seconds;
document.getElementById(ids).innerHTML = op;
if (distance < 0) {
clearInterval(x);
document.getElementById(ids).innerHTML = "00:00:00";
$('a#'+ids).removeClass('a').addClass('aa');
}
}, 1000);
}
Here, a screenshot of the error;
Upvotes: 1
Views: 4419
Reputation: 590
The issue here is that some browsers (chrome) will accept '2018-06-14 11:59 AM' as a valid date string for new Date()
. Other browsers (firefox) do not. Your function is trusting the date string as valid when it should either accept a date object that has been pre-verified elsewhere or it should process your specific date string format as if it won't be valid.
Here's an example fix:
const dateParts = dt.split(' ') // ['2018-06-14', '11:59', 'AM']
const timeParts = dateParts[1].split(':') // ['11', '59']
const day = dateParts[0] // '2018-06-14'
const hours = parseInt(timeParts[0]) // 11
const minutes = parseInt(timeParts[1]) // 59
var countDownDate = new Date(day)
countDownDate.setHours(hours)
countDownDate.setMinutes(minutes)
Edit: changing the source date format is way easier, this solution assumes you can't.
Upvotes: 0
Reputation: 1531
It occurs parsing error in IE here:
var dt = '2018-06-14 11:59 AM';
var countDownDate = new Date(dt).getTime();
// is not valid date
so you have to change the date string format of dt like.
var dt = '2018/06/14 11:59 AM';
var countDownDate = new Date(dt).getTime();
// work fine in IE
Upvotes: 1
Reputation: 1622
The dt
value you accept as an argument is not a number, causing all of those calculations to result in NaN.
We can provide more information if you show how you pass value as dt
argument to your function.
Upvotes: 0