【问题标题】:FormatDistanceToNowStrict is displaying wrong dayFormatDistanceToNowStrict 显示错误的日期
【发布时间】:2021-09-10 00:10:26
【问题描述】:
console.log(dateFns.formatDistanceToNowStrict(new Date(2021,08,23),
{ unit:'day'})) // returns 87 days when it should be 58 days

console.log(dateFns.format(new Date(), 'dd.MM.yyyy')) //displays the correct current date

我不知道为什么它在我的 discord.js 机器人上显示 87 天而不是 59 天(这就像整整一个月,不要认为这是一个时区问题)。

知道它可能有什么问题,我正在尝试从现在到另一个日期之间的时间,并且我正在使用 Date Fns,四舍五入也不起作用

【问题讨论】:

    标签: javascript date discord.js date-fns


    【解决方案1】:

    好吧,想办法。

    console.log(dateFns.formatDistanceToNowStrict(new Date(2021,08,23),
    { unit:'day'}))
    

    将日期格式更改为

    console.log(dateFns.formatDistanceToNowStrict(new Date('2021-08-23'),
    { unit:'day'}))
    

    【讨论】:

    • new Date(2021,08,23) 为 2021 年 9 月 23 日创建本地日期,而 new Date('2021-08-23') 为 2021 年 8 月 23 日创建 UTC 日期。
    【解决方案2】:

    你的问题很简单。 new Date() 构造函数中的月份是 0 索引的。这意味着如果您想将 08(八月)设置为您的月份,您实际上必须通过 07,因为一月是 00 而不是 01。

    // With 08 as month ❌
    const difference1 = new Date(2021, 08, 23) - new Date();
    console.log(`08: ${difference1 / 1000 / 60 / 60 / 24} days`);
    
    // With 07 as month ✔️
    const difference2 = new Date(2021, 07, 23) - new Date();
    console.log(`07: ${difference2 / 1000 / 60 / 60 / 24} days`);

    【讨论】:

    猜你喜欢
    • 2013-12-16
    • 2018-03-22
    • 2015-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-23
    • 1970-01-01
    相关资源
    最近更新 更多