gpt4 book ai didi

javascript - Safari 日期差异给出了 nan

转载 作者:行者123 更新时间:2023-11-28 04:30:29 25 4
gpt4 key购买 nike

我正在使用一个函数从今天的日期和时间中减去特定的日期和时间

<script>
function timeDifference(previous) {

var msPerMinute = 60 * 1000;
var msPerHour = msPerMinute * 60;
var msPerDay = msPerHour * 24;
var msPerMonth = msPerDay * 30;
var msPerYear = msPerDay * 365;

var elapsed = new Date() - new Date(previous);

if (elapsed < msPerMinute) {
return Math.round(elapsed/1000) + ' seconds ago';
}

else if (elapsed < msPerHour) {
return Math.round(elapsed/msPerMinute) + ' minutes ago';
}

else if (elapsed < msPerDay ) {
return Math.round(elapsed/msPerHour ) + ' hours ago';
}

else if (elapsed < msPerMonth) {
return Math.round(elapsed/msPerDay) + ' days ago';
}

else if (elapsed < msPerYear) {
return Math.round(elapsed/msPerMonth) + ' months ago';
}

else {
return Math.round(elapsed/msPerYear ) + ' years ago';
}
}
</script>

这个函数在 firefox、chrome 上完美运行,但在 safari 上给出 NaN知道为什么会发生这种情况吗?

最佳答案

使用时刻而不是日期,一切正常

 <script>
function timeDifference(previous) {

var msPerMinute = 60 * 1000;
var msPerHour = msPerMinute * 60;
var msPerDay = msPerHour * 24;
var msPerMonth = msPerDay * 30;
var msPerYear = msPerDay * 365;

var elapsed = new moment() - new moment(previous);

if (elapsed < msPerMinute) {
return Math.round(elapsed/1000) + ' seconds ago';
}

else if (elapsed < msPerHour) {
return Math.round(elapsed/msPerMinute) + ' minutes ago';
}

else if (elapsed < msPerDay ) {
return Math.round(elapsed/msPerHour ) + ' hours ago';
}

else if (elapsed < msPerMonth) {
return Math.round(elapsed/msPerDay) + ' days ago';
}

else if (elapsed < msPerYear) {
return Math.round(elapsed/msPerMonth) + ' months ago';
}

else {
return Math.round(elapsed/msPerYear ) + ' years ago';
}
}
</script>

关于javascript - Safari 日期差异给出了 nan,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44653583/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com