【问题标题】:difference in calendar days, solution other than date-fns/moment?日历日的差异,日期-fns/时刻以外的解决方案?
【发布时间】:2020-11-10 03:32:27
【问题描述】:

我试图获得 2 个日期之间的天数差异,即 7 月 17 日和 7 月 19 日相差 2 天。我目前正在使用 date-fns 库并利用差异 InCalendarDays 不幸的是,这是不准确的,它返回 7 月 17 日和 7 月 19 日之间的 1 天差异。我创建了这个 repl 来演示该方法的不准确功能。我也尝试过使用 momentjs 并得到相同的结果。

回复 - https://repl.it/@yazmnh87/CumbersomeLightsalmonTheories#index.js

gitHub 发布日期-fns - https://github.com/date-fns/date-fns/issues/1877

我想到的一个解决方案是在保存到数据库之前将时间设置为中午或其他时间,这样我就能得到一致的结果。非常感谢任何有关如何轻松解决此问题的帮助。

【问题讨论】:

    标签: javascript


    【解决方案1】:

    不确定date-fns 可能有什么问题

    但你可以在没有库的情况下实现这一点:

     const difference = new Date("Sun Jul 19 2020 15:13:20 GMT-0600 (Mountain Daylight Time)") - new Date("Fri Jul 17 2020 21:15:40 GMT-0600 (Mountain Daylight Time)")
    // the difference is in miliseconds.
    // divide it by miliseconds in a day to get the difference in days
    const differenceInDays = Math.round(Math.abs((difference) / (24 * 60 * 60 * 1000)))
     
    console.log(differenceInDays)

    【讨论】:

    • 谢谢,我试试看:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多