Comparing client and server times

I have a Node.js server that queries an API to receive a set of times like this:

{
  "end": "2014-05-24T14:00:00.000Z",
  "start": "2014-05-24T11:00:00.000Z"
}

The client's browser makes AJAX GET requests to the server, passing in the client's local time in ms:

// ajax code
data: { localTime: (new Date()).getTime() }
// more ajax code

I want to compare to the time that the server receives and check whether it lies within the interval defined by the API's events.

The data returned by the API define events on the east coast, and when I pass these strings into the Date constructor they are parsed into the Eastern timezone.

The issue arises because of Daylight time savings, and the fact that the client could be in a different timezone than the server or EST.

I've become pretty confused trying to convert all of the times to the same timezone, so I'm really not sure how I should go about doing this in the most reliable way.

Any help is greatly appreciated!


You probably don't want to use (new Date()).getTime()

You might consider new Date().toISOString() instead, which returns a string in the same format as your end and start .

Here's a runnable example:

var times = {
  "start": "2014-11-11T11:11:11.000Z",
  "end": "2014-12-12T12:12:12.000Z"
}

var data = {
  localTime: new Date().toISOString()
}

if (new Date(data.localTime) > new Date(times.start) && new Date(data.localTime) < new Date(times.end))
  document.body.innerHTML = "Client time is within the interval";
else
  document.body.innerHTML = "Client time is not within the interval";
链接地址: http://www.djcxy.com/p/86176.html

上一篇: 毫秒比较在PHP中

下一篇: 比较客户端和服务器时间