首页 > 解决方案 > Javascript 仅在 IOS 浏览器中返回 NaN

问题描述

我正在制作这个年龄计算器网站,它在 JS 中使用 Date 对象,并通过减去当前时间(以毫秒为单位)和用户的出生日期(以毫秒为单位)计算他们的年龄以不同的单位(年、月、日等)并将其输出到html。

它在 windows 和 android 上是完全可用的,但是,当网站在 IOS 中加载时,它会返回 NaN。我不知道它是否与 parseInt() 函数或在这两个平台中自动完成而在 IOS 中没有完成的事情有关。这是供参考的网站:https ://hesamzakeri.ir/en/

    <div id="years"></div>
    <div id="months"></div>
    <div id="days"></div>
    <div id="hours"></div>
    <div id="minutes"></div>
    <div id="seconds"></div>

<script>
    let currentTime = Date.now();

    let birthday = new Date(2002 + '-' + 07 + '-' + 04); // example

    let birthday = Date.parse(birthday);

    let age = currentTime - birthday;

    let yearsOld = parseInt(age / 1000 / 60 / 60 / 24 / 365, 10);

    let yearsOldInMs = yearsOld * 365 * 24 * 60 * 60 * 1000;

    let monthsOld = parseInt((age - yearsOldInMs) / 1000 / 60 / 60 / 24 / 30.417, 10);

    let monthsOldInMs = monthsOld * 30.417 * 24 * 60 * 60 * 1000;

    let daysOld = parseInt((age - (yearsOldInMs + monthsOldInMs)) / 1000 / 60 / 60 / 24, 10);

    let daysOldInMs = daysOld * 24 * 60 * 60 * 1000;

    let hoursOld = parseInt((age - (yearsOldInMs + monthsOldInMs + daysOldInMs)) / 1000 / 60 / 60, 10);

    let hoursOldInMs = hoursOld * 60 * 60 * 1000;

    let minutesOld = parseInt((age - (yearsOldInMs + monthsOldInMs + daysOldInMs + hoursOldInMs)) /
                1000 /
                60,
            10
        );

    let minutesOldInMs = minutesOld * 60 * 1000;

    let secondsOld = parseInt(
            (age -
                (yearsOldInMs +
                    monthsOldInMs +
                    daysOldInMs +
                    hoursOldInMs +
                    minutesOldInMs)) /
                1000,
            10
        );
</script>

这是计算年龄的部分之一。我省略了 JS 中不必要的部分,例如它将结果输出到 HTML 的位置。

标签: javascripthtmlioswebnan

解决方案


您将 Date 对象传递给Date.parse(),这需要一个字符串。

你的代码:

birthday = new Date(formYear + '-' + formMonth + '-' + formDay);

birthday = Date.parse(birthday); // NaN

将最后一行更改为:

birthday = Date.parse(birthday.toString());

更新:

OP 评论说问题出在非标准日期字符串输入到new Date(),而不是调用Date.parse().

日期字符串输入已修复,但调用Date.parse()仍然是错误的(尽管某些浏览器可能仍然可以使用它)。

// this is correct
birthday = new Date(2001, 2, 4);
console.log(typeof birthday); // object

// this is NOT correct, argument to Date.parse is type 'object'
// (Date.parse argument must be type 'string')
birthday = Date.parse(birthday);

// this is what you want:
let birthTime = birthday.getTime();

Date.parse 需要一个字符串参数,来自MDN

dateString
一个字符串,表示 ISO 8601 日历日期扩展格式的简化。(可以使用其他格式,但结果取决于实现。)

即使将有效的日期字符串传递给 Date.parse,您也应该完全避免使用 Date.parse,因为不同的主机以不同的方式解析日期字符串。来自 MDN:

在 ES5 之前不建议使用Date.parseas,字符串的解析完全依赖于实现。不同主机解析日期字符串的方式仍然存在许多差异,因此应该手动解析日期字符串(如果要适应许多不同的格式,库可以提供帮助)。


推荐阅读