Reputation: 731
I am trying to calculate difference between 2 times. But it is not working as I expected.
e.g: In the following photo
- current Time
- item created Time
- current Time converted to millisecond
- created Time converted to millisecond
- current - created (millisecond)
As shown image, I expected the difference 17h 19min 27s. But it gave me 5h 19min 27s. (Just 12 hours difference)
I am not sure that is AM(PM) problem or Time zone problem. I used following method.
<Text red>{dayjs(new Date().getTime()).format('YYYY-MM-DD HH:mm:ss')}</Text>
<Text red>{dayjs(new Date(`${item.created_at.slice(0, 10)}T${item.created_at.slice(11, 19)}`).getTime()).format('YYYY-MM-DD hh:mm:ss')}</Text>
<Text red>{new Date().getTime()}</Text>
<Text red>{new Date(`${item.created_at.slice(0, 10)}T${item.created_at.slice(11, 19)}`).getTime()}</Text>
<Text red>{new Date().getTime()-new Date(`${item.created_at.slice(0, 10)}T${item.created_at.slice(11, 19)}`).getTime()}</Text>
How can I get exact difference? In a word, new Date().getTime()
is not working as I expected.
Upvotes: 1
Views: 4153
Reputation: 13078
This way I am getting the correct value.
const printRemainingTime = (t2) => {
const t1 = new Date().getTime();
let ts = (t1-t2.getTime()) / 1000;
var d = Math.floor(ts / (3600*24));
var h = Math.floor(ts % (3600*24) / 3600);
var m = Math.floor(ts % 3600 / 60);
var s = Math.floor(ts % 60);
console.log(d, h, m, s)
}
printRemainingTime(new Date("2020-11-26T06:29:33"));
See: https://stackblitz.com/edit/js-xqdk64
Upvotes: 1
Reputation: 624
I ll suggest u to use date-fns library
var differenceInMilliseconds = require('date-fns/differenceInMilliseconds')
differenceInMilliseconds(dateLeft, dateRight)
Upvotes: 2