且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用moment.js计算出错误的日期差

更新时间:2023-01-31 14:40:37

简短答案:

正如约翰·马达哈文·里斯(John Madhavan-Reese)在回答中所说,您必须使用时刻持续时间表示两个时刻之间的差异.

Short answer:

As John Madhavan-Reese stated in his answer, you have to use moment Duration to represent the diffecence between two moments in time.

在您的代码中,您将根据expirationtoday之间的差异创建一个矩对象.此值瞬间解释为自Unix纪元以来的毫秒数(请参见 moment(Number) ),因此您将在1970年1月1日前后的任意一天创建一个矩对象(请参见moment(expiration- today).format()的输出). format() 中的D令牌代表月日,因此给出不正确" 输出.

In your code you are creating a moment object from the difference between expiration and today. This value is interpreded by moment as the number of milliseconds since the Unix Epoch (see moment(Number)), so you are creating a moment object for a random day around the 1st January 1970 (see the output of moment(expiration- today).format() ). The D token in format() stands for Day of Month, so it gives an "incorrect" output.

您可以使用momentjs' diff() 计算差异,然后创建 moment.duration(Number) .

You can calculate difference using momentjs' diff() then you can create a duration using moment.duration(Number).

最后,您可以使用 moment-duration-format 插件获得所需的输出在(作者:John Madhavan-Reese:D)

Finally you can get your desired output using moment-duration-format plug-in (by John Madhavan-Reese :D)

这里有一个现场样本:

function getDiff(value) {
     var expiration= moment(value); // Parse input as momement object
     var today = moment(); // get now value (includes current time)
     // Calculate diff, create a duration and format it
     var dayToExpiration = moment.duration(Math.abs(today.diff(expiration))).format('D[days], H[hours]');

     console.log(today.format('DDMMYYYY') + " : " + expiration.format('DDMMYYYY'));
     console.log(dayToExpiration);
}

getDiff('2018-10-28');

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/2.2.2/moment-duration-format.min.js"></script>