0

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?

Brendan Jackson
  • 305
  • 1
  • 3
  • 13
  • If I **HAD** to guess, I'd say it's because of the way you have `deadline` formatted. I'd format it like DD/MM/YY and not DD MM YY (with spaces). –  May 10 '17 at 01:45
  • It could be date.parse() according to [this](http://stackoverflow.com/questions/6427204/date-parsing-in-javascript-is-different-between-safari-and-chrome) but then again the question is old so compatibility could have been fixed since then. – Dana May 10 '17 at 01:49
  • Please see [*Why does Date.parse give incorrect results?*](http://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results). – RobG May 10 '17 at 02:22

1 Answers1

2

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.

Community
  • 1
  • 1
RobG
  • 142,382
  • 31
  • 172
  • 209