2

On my app users can posts comments and specify the comment's expire datetime.

The process is simple:

They choose a date and the date is inserted inside DB with the comment by PHP in format (Y-m-d H:m:s).

Then when i visualize comments i put a JS countdown on each one comment.

Countdown is calculated by JS from the current JS datetime until the DB stored expiration_datetime CONVERTED IN JS,and this is for each one comment.

So i'm wondering while, inserting i use PHP, then outputting i use JS, will this produce any problem related to timezones and user's browsers datetime vs server datetime?

in PHP i do:

$expiration_datetime = date('Y-m-d H:m:s');

in JS i convert :

var expiration_datetime = new Date(<?php $expiration_datetime[0]?>,<?php $expiration_datetime[1]?>,<?php $expiration_datetime[2]?>,<?php $expiration_datetime[3]?>,<?php $expiration_datetime[4]?>,<?php $expiration_datetime[5]?>,);

So i'm wondering if converting datetime by JS will produce any kind of problem for users with different timezones, at the end, what you suggest to pay attention on, or to do, for using best practices out there?

MORE ABOUT:

i'm thinking that maybe setting server and js fixed timezone for dates and datetimes will be unique for all users coming to site, did you agree?

4

2 回答 2

1

JavaScript Date() 对象将日期存储为距纪元 (01/01/1970) 的毫秒数的偏移量,因此以您建议的方式简单地构造日期将考虑用户的时区。

如果您将存储在数据库中的日期标准化为 GMT,那么您可以采用带和大括号的方法并使用:

var expiration_datetime = new Date(Date.UTC(
    <?php $expiration_datetime[0]?>, <?php $expiration_datetime[1]?>,
    <?php $expiration_datetime[2]?>, <?php $expiration_datetime[3]?>,
    <?php $expiration_datetime[4]?>, <?php $expiration_datetime[5]?>,
));

这应该向 JS 解析器表明它正在接收的日期信息是 GMT。

于 2012-11-02T09:54:57.090 回答
0

使用 unix 时间戳并使用 buildin JS Date 构造函数从中构造日期:

php:  time()
js: new Date(ms)

注意:php 函数返回秒,js - 使用毫秒。不要忘记乘以 1000

于 2012-11-02T09:41:41.187 回答