Prosto Trader
Prosto Trader

Reputation: 3527

Get time diffrence between local and remote time

Yes, I know about thousands of look-a-like questions, but my brain is trying to blow and I ask you for help. I've read nuomerous articles and still confused.

Here is what I have.

var next_market_event_in_NewYork = "2014-12-02T16:00:00"; //that's what server gives me
var secondsFromMarketToMoscow = 28800; //that's also what server gives me
var secondsFromMoscowToLondon = 10800; //that's also what server gives me 
var secondsFromLocalToLondon = 7200; //that's what I get from local timeoffset new Date().getTimezoneOffset()*(-60)

What I need is how many seconds left from now locally to next event in New York. Spent on this dozens of hours. Just don't get how to get the answer. Pls help.

Upvotes: 0

Views: 386

Answers (2)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241475

If you require a pure JavaScript solution, consider using a library that already understands time zones, such as moment.js with the moment-timezone add on.

var next_market_event_in_NewYork = "2014-12-02T16:00:00";
var m = moment.tz(next_market_event_in_NewYork, "America/New_York");
var now = moment();
var s = m.diff(now,'seconds');

Upvotes: 0

Dave
Dave

Reputation: 10924

The difficult part is calculating the difference between New York time and UTC. If you can do this server-side you should have no problem. If you can't then you can hardcode the offset, but that changes when USA is on Daylight time.

Here's a code example with a hardcoded 5 hour offset between NY and UTC.

var next_market_event_in_NewYork = "2014-12-02T16:00:00";
var msNYtoUTC = 5 * 60 * 60 * 1000; //better to calculate this server-side
var nextEventDate = new Date(Date.parse(next_market_event_in_NewYork) + msNYtoUTC);

setInterval(function() {
  var localTime = new Date();
  var secondsRemaining = (nextEventDate - localTime) / 1000;
  document.getElementById("result").innerHTML = secondsRemaining.toFixed(0);
}, 1000);
<h1>
  <span id="result"></span>
  seconds until market event
</h1>

Upvotes: 1

Related Questions