简体   繁体   中英

How can you subtract dates with different time formats in JavaScript?

I'm working with an API that returns dates in the following format:

2020-06-08 22:51:11 -0300

and I need to calculate how much time has elapsed until certain event happens for which I'm using Date.now() which outputs milliseconds since 1970.

1591667758424

So I got two time formats what I can't subtract. What is the best solution to work with both?

You can convert the string date to the same format using getTime , doing like that:

const date = new Date('2020-06-08 22:51:11 -0300').getTime()
console.log(date - 1591667758424 )

I think the calcuation should be performed like this

srvtmili= new Date('2020-06-08 22:51:11').getTime()
h=60*60*1000
timedifference=4*h //3 hours from UTC and 1 hour (dls) from GMT 
srvrtimeconvtolocal=timedifference+srvtmili //convert to local GMT in this case
localtimeinmil=1591667758424
timedifference=1591667758424-srvrtimeconvtolocal
console.log('difference is',timedifference/(1000),'in 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