Home > OS >  Date in iOS shows NaN
Date in iOS shows NaN

Time:07-24

I'm making this website with a countdown using javascript. When I deploy the website, everything is working fine in android and windows, but when I open the website on my iOS device the countdown turns into "NaN". Can anyone help me fix this problem? Thanks in advance!

This is my countdown JavaScript code:

const newDate = new Date(serverTime).getTime();
const countdown = setInterval(() => {
    const date = new Date().getTime();
    const diff = newDate - date;

    const days = Math.floor(
        (diff % (1000 * 60 * 60 * 24 * (365.25 / 12))) / (1000 * 60 * 60 * 24)
    );
    document.querySelector(".days").innerHTML = days < 10 ? "0"   days : days;

    if (date >= newDate) {
        clearInterval(countdown);
        document.querySelector(".days").innerHTML = "00";
    }
}, 1000); 

CodePudding user response:

What is the format of serverTime?

When parsing date strings with the Date constructor (and Date.parse, they are equivalent), always make sure that the input conforms to the ISO 8601 format (YYYY-MM-DDTHH:mm:ss.sssZ) — the parsing behavior with other formats is implementation-defined and may not work across all browsers.

Source

So if your serverTime string is not in this format, you’ll have unpredictable results.

If you need to parse a date from a different format, use a library such as date-fns.

  • Related