简体   繁体   English

日历日的差异,日期-fns/时刻以外的解决方案?

[英]difference in calendar days, solution other than date-fns/moment?

Im trying to just get the difference in days between 2 dates ie july 17th and july 19th is a difference of 2 days.我试图获得两个日期之间的天数差异,即 7 月 17 日和 7 月 19 日相差 2 天。 Im currently using the date-fns library and utilizing the differenceInCalendarDays and unfortunately this is inaccurate it returns 1 day difference between july 17th and july19th.我目前正在使用 date-fns 库并利用差异 InCalendarDays 不幸的是,这是不准确的,它返回 7 月 17 日和 7 月 19 日之间的 1 天差异。 Ive created this repl to demonstrate the inaccurate functionality of the method.我创建了这个 repl 来演示该方法的不准确功能。 I've also tried using momentjs and am getting the same result.我也尝试过使用 momentjs 并得到相同的结果。

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

gitHub issue date-fns - https://github.com/date-fns/date-fns/issues/1877 gitHub 问题日期-fns - https://github.com/date-fns/date-fns/issues/1877

one solution I've thought of is setting the times to noon or something before saving to the DB so I get consistent results.我想到的一种解决方案是在保存到数据库之前将时间设置为中午或其他时间,以便获得一致的结果。 Any help on how to approach this easily is greatly appreciated.非常感谢有关如何轻松解决此问题的任何帮助。

not sure what might be the problem with date-fns不确定date-fns可能有什么问题

But you can achieve this without a library:但是你可以在没有库的情况下实现这一点:

 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM