Brendan Jackson
Brendan Jackson

Reputation: 335

Simple JS works on every browser but safari

Common headache, but each answer seems to be unique, I have some simple JS counting down until december 15th, this countdown works on each browser except I get 'NaN' for each day, hour, minute on safari.

<p id="clockdiv" class="decofont ">
<span class="days"></span>
<span class="hours"></span>
<span class="minutes"></span></p>
<!--302 D | 21 H | 48 M december 15 2017 -->

var deadline = '12 15 2017';

function getTimeRemaining() {
    var t = Date.parse('12 15 2017') - Date.parse(new Date());
    var seconds = Math.floor((t / 1000) % 60);
    var minutes = Math.floor((t / 1000 / 60) % 60);
    var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
    var days = Math.floor(t / (1000 * 60 * 60 * 24));

    var time = {
        'total': t,
        'days': days,
        'hours': hours,
        'minutes': minutes,
        'seconds': seconds
    };

    var output_time = document.getElementById('clockdiv');
    output_time.innerHTML = days + ' D | ' + hours + ' H | ' + minutes + ' M';
    setTimeout(getTimeRemaining, 60000);
}


getTimeRemaining(deadline);

Bonus points if you have a link to JS cross browser compatibility (common functions that don't work on all browsers). What is causing this to break on safari and what is the most simple alternative?

Upvotes: 0

Views: 219

Answers (1)

RobG
RobG

Reputation: 147553

The root of your issue is that you are parsing a string and expecting all browsers to parse it the same. Parsing of date string is almost entirely implementation dependent, there is only one format (ISO 8601 extended) that ECMA-262 requires to be supported.

So in the line:

var t = Date.parse('12 15 2017') - Date.parse(new Date());

you should use the Date constructor. Also, you should not use Date.parse(new Date()), just use new Date or Date.now() so:

var t = new Date(2017,11,15) - new Date();

which will return the difference in milliseconds between the two dates:

console.log(new Date(2017,11,15) - new Date());

Also see Difference between dates in JavaScript.

Upvotes: 2

Related Questions