简体   繁体   中英

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. 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. Ive created this repl to demonstrate the inaccurate functionality of the method. I've also tried using momentjs and am getting the same result.

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

gitHub issue date-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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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