开发者

Why is there a difference between JavaScript and PHP timestamp

I have created a JavaScript timestamps and also a PHP timestamp. There is about 170 sec difference between them.

  • 1302162686 PHP - time()
  • 1302162517 JavaScript - Math.round(new Date().getTime() / 1000)

Can anyone please tell me why I'm having this iss开发者_开发知识库ue?


PHP is executed on the server side, and in your example, JavaScript works on the client-side.

Both sides have their own time configuration. For the server, time zone settings etc. will stay the same (unless you change them), but the server has no idea which time zone the current visitor is in. There’s no way for you to control that.

If I change my system clock on my laptop, it will influence client-side JavaScript date/time, but your server timer won’t be affected.


PHP and JavaScript, both look at the system time. Whose system? The one they are running on. The server could be located in another country with different time, hence the difference.

Also, the client's (or less often, server's) clock could be incorrect.

One way, which I often use to counter this problem is like this:

var referenceTime = new Date('<?php echo date("M n, Y"); ?>');
// referenceTime is now the same as server time


PHP looks at the system time, which is the server running it.

JavaScript looks at the client's system, which could be any time.


php uses the time on your server, javascript will use the time on the client (users) machine.


Mathias is correct. Generally this should not happen with that big a difference because modern computers recognize their clocks drift over time and employ protocols such as NTP to keep their clocks in sync.

Nevertheless you should never assume the time at client and server is the same, for two reasons:

  • Some clients/servers don't have clock adjustments (such as NTP) and their clocks drift away over time
  • More importantly, many users/admins can be clueless or late in setting their time zone or adjusting daylight savings times, so the time given to you may be accurate to a second but be several hours off.

When comparing/calculating times, I would rely on the server only. You have no control over the client.


If you are concerned about consistency for whatever purpose, I recommend using the server as your time source and do timezone conversions if necessary:

This may be of interest: handling timezone conversion with php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜