简体   繁体   中英

How to calculate difference between 2 times in React Native?

I am trying to calculate difference between 2 times. But it is not working as I expected.

eg: In the following photo

  1. current Time
  2. item created Time
  3. current Time converted to millisecond
  4. created Time converted to millisecond
  5. 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.

I ll suggest u to use date-fns library

var differenceInMilliseconds = require('date-fns/differenceInMilliseconds')
differenceInMilliseconds(dateLeft, dateRight)

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

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