如何在 JavaScript 中获取服务器日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13889853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the Server date in JavaScript
提问by Aniket
I am working on a small project where I am dealing with dates.
我正在处理一个处理日期的小项目。
In order to get the today's date, I'm currently using the following JavaScript code:
为了获得今天的日期,我目前使用以下 JavaScript 代码:
var today = new Date();
However, this results in the current date set on the client system, which may vary between systems, and hence the final output is different.
但是,这会导致在客户端系统上设置当前日期,该日期可能因系统而异,因此最终输出不同。
So in order to get the same result on all clients, I need to know the current date from the server. How can I get the server date in JavaScript?
因此,为了在所有客户端上获得相同的结果,我需要知道服务器的当前日期。如何在 JavaScript 中获取服务器日期?
回答by Taha Jahangir
Definitely getting server date is not possible without querying server.
如果不查询服务器,肯定无法获得服务器日期。
So do a separate AJAX call to get the server date, or if your application already sends some ajax query, place the date in Dateheader in server-side, and read it in client.
所以做一个单独的 AJAX 调用来获取服务器日期,或者如果您的应用程序已经发送了一些 ajax 查询,请将日期Date放在服务器端的标头中,然后在客户端读取它。
Also if you entire page is served dynamically (like PHP), place server side date in html source like this:
此外,如果您的整个页面是动态提供的(如 PHP),请将服务器端日期放在 html 源中,如下所示:
<script>
var serverDate = <?= time() ?>
var dateDiff = new Date - serverDate;
</script>
回答by user1321471
javascript runs on the client side, so will return the date of the client.
javascript 在客户端运行,因此将返回客户端的日期。
To get the date of the server, you would most likely want to use a server side language such as asp.net, php, etc.
要获取服务器的日期,您很可能希望使用服务器端语言,例如 asp.net、php 等。
回答by HBP
You can send your server date/time in the web page and have the JavaScript determine the difference between that and the browser date.
您可以在网页中发送您的服务器日期/时间,并让 JavaScript 确定该日期与浏览器日期之间的差异。
Depending on your exact requirements, you might also consider using UTC date/time which, as its name implies, is universal.
根据您的具体要求,您还可以考虑使用 UTC 日期/时间,顾名思义,它是通用的。

