我使用日期-fns来计算日差
import differenceInDays from "date-fns/differenceInDays";
console.log(
differenceInDays(
new Date("2020-08-12T07:22:03.498Z"),
new Date("2020-08-09T09:30:20.914Z")
)
);答案是2,我期待3,因为12-9是3。
怎么了?https://codesandbox.io/s/date-fns-v2-pzlex?file=/src/index.js:0-299
发布于 2020-08-09 11:23:27
整日差异
只使用一整天的原因是,API是按照DifferenceInDays的正式文档工作的。
日历日差异
您要寻找的是日历日的差异,这是date-fns本机支持的,如differenceInCalendarDays的文档所示。
水下这个API只是剥夺了时间,这似乎是你正在寻找的。
示例
import differenceInCalendarDays from "date-fns/differenceInCalendarDays";
console.log(
differenceInCalendarDays(
new Date("2020-08-12T07:22:03.498Z"),
new Date("2020-08-09T09:30:20.914Z")
)
);发布于 2020-08-09 11:16:03
如果只想获得日期,请删除时区的时间。
console.log(
differenceInDays(
new Date("2020-08-12"),
new Date("2020-08-09")
)
);
// returns 3发布于 2020-08-09 11:16:12
它应该显示给定日期之间的整日数。(你整整三天都没有几个小时)
因此,如果将最后日期时间更改为new Date("2020-08-12T09:30:20.914Z")
它将显示三天。
https://stackoverflow.com/questions/63325543
复制相似问题