Moment.js diff 返回零,即使存在差异

问题描述 投票:0回答:4

我想在几分钟内找出两个日期对象之间的差异。问题是当日期对象相同时,它返回零。但是当差异变为 1 时,差异也返回零。

我的代码如下

let currentDate = Moment();
let takenDateString = `${currentDateString(date)} ${hours}:${minutes} ${isAM ? 'AM' : 'PM'}`
let takenDate = Moment(takenDateString, 'YYYY-MM-DD hh:mm A');

console.log("=======================")
console.log(currentDate.format('YYYY-MM-DD hh:mm A'))
console.log(takenDateString);
console.log(takenDate.diff(currentDate, "minutes"));
console.log("=======================")

这也是打印在日志中的内容

Util.js:62 =======================
Util.js:63 2019-09-04 03:26 PM
Util.js:64 2019-09-04 03:26 PM
Util.js:65 0
Util.js:66 =======================
Util.js:62 =======================
Util.js:63 2019-09-04 03:26 PM
Util.js:64 2019-09-04 03:26 PM
Util.js:65 0
Util.js:66 =======================
Util.js:62 =======================
Util.js:63 2019-09-04 03:26 PM
Util.js:64 2019-09-04 03:27 PM
Util.js:65 0
Util.js:66 =======================
Util.js:62 =======================
Util.js:63 2019-09-04 03:26 PM
Util.js:64 2019-09-04 03:28 PM
Util.js:65 1
Util.js:66 =======================

你会看到上面的行为。即使时差为 1,它也返回零,而当它为 2 时,它返回 1。为什么会有这种奇怪的行为?

javascript date ecmascript-6 momentjs
4个回答
2
投票

查看 Moment 中 diff 函数的源代码,我们看到它采用分钟和地板差的绝对值。因此,例如 0.5 分钟变为 0,1.9 分钟变为 1.

将第三个参数作为

true
传递给
diff()
会给你一个浮点数的答案(可以是负数)。

let a = moment("2019-09-04T09:33:30.000");
let b = moment("2019-09-04T09:34:00.000");
a.diff(b, "minutes") // -> 0
a.diff(b, "minutes", true) // -> -0.5

如果你想要“时钟分钟”的差异,你可以使用

minutes()

let a = moment("2019-09-04T09:33:30.000");
let b = moment("2019-09-04T09:34:00.000");
b.minutes() - a.minutes() // -> 1

0
投票

Moment 截断(即向下舍入)差异(因此 59 秒将变为 0 分钟)。

https://momentjs.com/docs/#/displaying/difference/


0
投票

我认为我们需要让时刻知道我们的日期是哪种格式

// My code when the result is 0 even tho it's not supposed to
// I thought x and y were supposed to have the same format so I did this
const x = moment('2020-12-28T17:00:00.000Z', "DD/MM/YYYY"); 
const y = moment('30/04/2023');
const diff = y.diff(x, "years", true);  // diff = 0;

// While actually we should just clarify our dates' formats
// Below is the working version
const x = moment('2020-12-28T17:00:00.000Z', "YYYY-MM-DD");
const y = moment('30/04/2023', "DD/MM/YYYY");
const diff = moment(y).diff(x, "years", true);  // diff = 2.338888888888889;

-1
投票

您应该在将 takenDateString 传递给 moment 之前将其转换为日期对象。

编辑:您也可以使用字符串,但转换为日期对象对我有用。

let currentDate = Moment();
let takenDateString = `${currentDateString(date)} ${hours}:${minutes} ${isAM ? 'AM' : 'PM'}`
let takenDate = Moment(new Date(takenDateString), 'YYYY-MM-DD hh:mm A'); // pass a date object instead

console.log("=======================")
console.log(currentDate.format('YYYY-MM-DD hh:mm A'))
console.log(takenDateString);
console.log(takenDate.diff(currentDate, "minutes"));
console.log("=======================")
© www.soinside.com 2019 - 2024. All rights reserved.