Reputation: 5
I have two dates in millis 1513885098821 & 1513885078742.
How to display the difference between above two dates in hrs and mins like 2 hrs 31 mins
.
If moment have any option then its good, solution using plain javascript is also ok for me.
I tried below
moment(new Date(txn.toDate - txn.fromDate)).format('HH mm')
But it gives 05 30 result.
Output of below line is
new Date(1513885098821 - 1513885078742);
result: Thu Jan 01 1970 05:30:20 GMT+0530 (India Standard Time)
Upvotes: 0
Views: 72
Reputation: 3336
There are probably countless answers already to help you find the difference between two dates, either using moment js
or simply the native javascript Date object. Since you are having difficulty though, here is an example using moment js
and its diff
function:
// use timestamps to create moment objects
const startDate = moment.utc(1513885098821);
const endDate = moment.utc(1513885078742);
const hourDiff = startDate.diff(endDate, 'hours');
console.log(hourDiff); // 0
const minuteDiff = startDate.diff(endDate, 'minutes');
console.log(minuteDiff); // 0
const secondDiff = startDate.diff(endDate, 'seconds');
console.log(secondDiff); // 20
console.log(`${hourDiff}hrs ${minuteDiff}mins ${secondDiff}sec`); // 0hrs 0mins 20sec
Or try it online here.
Upvotes: 1
Reputation: 1413
try splitting string from the first method.
var k=moment(new Date(txn.toDate - txn.fromDate)).format('HH mm');
var frmt=k.split(' ');
var min=frmt+'mm';
var hr=frmt+'fr';
Upvotes: 0
Reputation: 3967
You don't need to use Date
, just do this:
prettyMillisDiff(millis1, millis2) {
let minDiff = (millis1 - millis2)/60000;
if (minDiff < 0) {
minDiff *= -1;
}
const hours = Math.floor(minDiff/60);
const mins = Math.floor(minDiff%60);
console.log(`${hours} hours ${mins} mins`);
}
Upvotes: 0