pinkfloyd90
pinkfloyd90

Reputation: 678

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?

Upvotes: 0

Views: 114

Answers (2)

Sven.hig
Sven.hig

Reputation: 4519

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')

Upvotes: 0

Tércio Garcia
Tércio Garcia

Reputation: 437

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 )

Upvotes: 2

Related Questions