Skip to content
Advertisement

Script works only on Chrome and Firefox Desktop, and not works on Safari and any mobile browser

I can’t understand why this script works only on Chrome and Firefox on Desktop, and not works on Safari Desktop and any mobile browser.

<span style="font-size:1.4rem;margin:0 .5rem;"><span id="days"></span> Days</span>
<span style="font-size:1.4rem;margin:0 .5rem;"><span id="hours"></span> Hours</span>
<span style="font-size:1.4rem;margin:0 .5rem;"><span id="minutes"></span> Minutes</span>
<span style="font-size:1.4rem;margin:0 .5rem;"><span id="seconds"></span> Seconds</span>

<script type="text/javascript">

    var second = 1000;
    var minute = second * 60;
    var hour = minute * 60;
    var day = hour * 24;

    var countDown = new Date('Apr 20, 2021 24:00:00').getTime();

    var x = setInterval(function () {

        var now = new Date().getTime();
        var distance = countDown - now;

        document.getElementById('days').innerText = Math.floor(distance / day),
        document.getElementById('hours').innerText = Math.floor(distance % day / hour),
        document.getElementById('minutes').innerText = Math.floor(distance % hour / minute),
        document.getElementById('seconds').innerText = Math.floor(distance % minute / second);
    }, second);

</script>

I’ve checked all the incompatibilities but I don’t seem to see any. Returned to me alloways NaN even if I use Number(...)

I just can’t understand.

Advertisement

Answer

Safari is a lot more strict on date formats.

I would suggest changing the format of your data string or manipulating it with Regex and so forth but it all gets a bit messy. One is assuming all your date data is going to be consistent?!

Example: https://codepen.io/alexpetergill/pen/39b775983b851e8fa14f1e548252d810

Just tested this on Big Sur / Safari 14

var months = {
  'Jan' : '01',
  'Feb' : '02',
  'Mar' : '03',
  'Apr' : '04',
  'May' : '05',
  'Jun' : '06',
  'Jul' : '07',
  'Aug' : '08',
  'Sep' : '09',
  'Oct' : '10',
  'Nov' : '11',
  'Dec' : '12'
}
  
function parseDate(s) {
  var dateTime = s.split(' ');
  var time = dateTime.pop();
  var day = dateTime[1].replace(/[, ]+/g, ' ').trim();
  var month = months[dateTime[0]];
  var year = dateTime[2];
  var date = new Date(year + '-' + month + '-' + day).toISOString().split('T')[0]
  return Date.parse(date + 'T' + time) // 2021-04-20T24:00:00
}
  
var countDown = parseDate('Apr 20, 2021 24:00:00');

The output of parseDate() is loosely based on the ECMAScript specification https://262.ecma-international.org/11.0/#sec-date-time-string-format

ECMAScript defines a string interchange format for date-times based upon a simplification of the ISO 8601 calendar date extended format. The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement