简体   繁体   中英

Difference between two dates and times in minutes [Javascript]

I have two strings which have dates as shown below:

var a = '2018-05-27T19:12:29.810Z'; var b = '2018-05-27T19:13:12.739Z'; I would like to get the time in minutes between these two dates (dates are now() functions from a server .

How can I achieve this?

Thus far I have tried below, however this doesn't work:

var dateA = new Date(a);
var dateB = new Date(b);
var x = (b-a);
console.log(x);

 var a = '2018-05-27T19:12:29.810Z'; var b = '2018-05-27T19:13:12.739Z'; var dateA = new Date(a); var dateB = new Date(b); var x = (dateB - dateA); console.log(Math.floor((x / 600) / 60), (x / 600) % 60); 

You can use momentjs's diff() to calculate the difference between dates in years , months , weeks , days , hours , minutes , and seconds .

'use strict';

let moment = require('moment');

let ma = new moment('2018-05-27T19:12:29.810Z');
let mb = new moment('2018-05-27T19:13:12.739Z');

console.log('Difference in hours => ', mb.diff(ma, 'hours'));
console.log('Difference in minutes => ', mb.diff(ma, 'minutes'));
console.log('Difference in seconds => ', mb.diff(ma, 'seconds'));

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