为什么 JavaScript 和 PHP 时间戳之间存在差异
我创建了一个 JavaScript 时间戳和一个 PHP 时间戳。它们之间大约有170秒的差异。
- 1302162686 PHP -
time()
- 1302162517 JavaScript -
Math.round(new Date().getTime() / 1000)
谁能告诉我为什么会遇到这个问题?
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 issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
PHP 在服务器端执行,在您的示例中,JavaScript 在客户端运行。
双方都有自己的时间配置。对于服务器来说,时区设置等将保持不变(除非您更改它们),但服务器不知道当前访问者位于哪个时区。您无法控制它。
如果我更改笔记本电脑上的系统时钟,它将影响客户端 JavaScript 日期/时间,但您的服务器计时器不会受到影响。
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和JavaScript,都看系统时间。谁的系统?他们正在运行的那个。服务器可能位于不同时间的另一个国家,因此存在差异。
此外,客户端(或偶尔是服务器)的时钟可能不正确。
我经常用来解决这个问题的一种方法是这样的:
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:
PHP 查看系统时间,即运行它的服务器。
JavaScript 会查看客户端的系统,这可能是任何时间。
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 使用服务器上的时间,javascript 将使用客户端(用户)计算机上的时间。
php uses the time on your server, javascript will use the time on the client (users) machine.
马蒂亚斯是正确的。一般来说,这种情况不应该发生那么大的差异,因为现代计算机认识到它们的时钟会随着时间的推移而漂移,并采用诸如 NTP 之类的协议 保持时钟同步。
然而,您永远不应该假设客户端和服务器的时间是相同的,原因有两个:
当比较/计算时间时,我只会依赖服务器。您无法控制客户。
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:
When comparing/calculating times, I would rely on the server only. You have no control over the client.
如果您担心出于任何目的的一致性,我建议使用服务器作为时间源,并在必要时进行时区转换:
这可能会令人感兴趣:使用 php 处理时区转换
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