如何在客户端(JavaScript)和服务器(PHP)之间均衡时区

时间:2017-08-05 05:09:26

标签: javascript php mysql cakephp timeago

我有一个普遍的问题,但此时我无法做到。我在一个项目上工作。我们的数据库基于欧洲/阿姆斯特丹时间。但是,客户时区和日期每次都在变化。你知道我在说什么' 我通过PHP(CakePHP)从数据库中获取日期。我只想在2分钟前和#34;写这些日期。我们将日期保存在数据库中,如#34; 2017-08-04 13:43:38"我可以将它用于其他问题或功能。 我使用timeago.js

我的问题

我现在正在通过界面更改任何记录。 (2017-08-04 13:43:38)(伊斯坦布尔时区)系统将2017-08-04 12:43:38(阿姆斯特丹时区)保存为修改日期。这就是为什么我的javascript始终显示大约一小时前它应该不到一分钟我想将每个客户时区更改为阿姆斯特丹时区。

我的问题:

  1. 我应该去哪里? (客户或服务器)
  2. 我尝试在客户端工作。如何通过javascript快速均衡时区?

2 个答案:

答案 0 :(得分:0)

Where I should do it? (client or server)

On the server as it has a host environment whose features and clock accuracy you can be confident of.

I tryna work on clientside. How to equalize timezone shortly by javascript?

If you are going to do it client side, you need to provide a string that will be parsed reliably on the client and that includes the timezone. You can use ISO 8601 format strings and hope that the client parses it correctly, or manually parse the string and make certain (a library can help but isn't mandatory).

Currently Amsterdam is UTC+0200 so you should send a string like "2017-08-04T13:43:38+0200" or "2017-08-04T11:43:38Z" and hope that the client clock is accurate.

If you use a library like moment.js you can get use it to parse the string and get a "friendly" format using fromNow like:

// Using date for Amsterdam
var d = moment("2017-08-05T13:43:38+0200");
console.log(d.format('D MMM YYYY [at] hh:mm A [local]') + ' was ' + d.fromNow() + '.');

// Equivalent UTC
var d = moment("2017-08-05T11:43:38Z");
console.log(d.format('D MMM YYYY [at] hh:mm A [local]') + ' was ' + d.fromNow() + '.');
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

Be careful with friendly formats, some really dislike them. Seeing "5 days ago" and "last week" when today is Tuesday makes me wonder which was before the other.

答案 1 :(得分:0)

如果您想要准确读取时间,可以使用Internet时间服务器来保证在整个平台上以毫秒级的粒度同步时间。在这里可以找到一些公共的http://tf.nist.gov/tf-cgi/servers.cgi。我会使用该客户端查找时间然后将其发送到服务器。我相信这些服务器将在ISO8601中服务。