我有一个页面显示 future 事件以及日期(服务器时间)。 我需要一些方法来显示用户时间中的日期。
例子:
10 月 26 日 13:48:23(服务器)
10月26日14:48:23(用户时间(UTC+1))->事件信息
我目前拥有的:
<?php
$sql=mysql_query("SELECT * FROM table") or die("Come back later");
while($row=mysql_fetch_array($sql)) {
echo date('M, d H:i:s', strtotime ($row['date'])).' -> '.$row['info'];
}
?>
不同的是我想检测用户时区。
谢谢。
编辑 我知道我不应该使用 mysql_*
最佳答案
如果您可以在 JavaScript 中转换为用户的时区,您可以执行以下操作:
PHP
<?php
$sql=mysql_query("SELECT * FROM table") or die("Come back later");
while($row=mysql_fetch_array($sql)) {
echo '<span class="date">' . date('M, d H:i:s', strtotime ($row['date'])) . ' UTC</span> -> '.$row['info'];
}
?>
JavaScript(使用 jQuery 提高可读性)
$(function(){
$('.date').each(function(){
var $this = $(this);
// Parse the date string (the format you've given will
// work, and the added UTC above will give JavaScript
// some context)
var dateVal = new Date($this.text());
// JavaScript will convert it to the user's timezone when
// stringifying it (helped by the server timezone specified
// in the PHP.
$this.text(dateVal.toString());
});
});
如果您想以以下格式呈现日期:Oct, 26 13:48:23
,您可以这样做:
var dateString = dateVal.toLocaleString();
var parts = /^\w+ (\w+ \d{1,2}) \d{4} (\d{2}:\d{2}:\d{2})/.exec(dateString);
dateString = parts[1] + ' ' + parts[2];
然后使用$this.text(dateString);
将其注入(inject)dom。
关于PHP JS 将日期转换为用户时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13088778/