Jer*_*ohn 7 php datetime timestamp date
我将$ item_date的原始生成的mysql时间戳信息从数据库中拉为php日期格式:
if (($timestamp = strtotime($item_date)) === false) {
echo "The timestamp string is bogus";
} else {
echo date('j M Y h:i:sA', $timestamp);
}
Run Code Online (Sandbox Code Playgroud)
服务器区域(UTC)的输出:
2012年11月12日05:54:11 PM
但我希望它根据用户时区进行转换
示例:假设用户的时间是2012年11月13日上午07:00:00(格林威治标准时间+0800),服务器时间是2012年11月12日下午11:00:00(UTC),$ item_date的时间戳是2012年11月12日10:30:00 PM(UTC)所以
(UTC)用户将$ item_date视为:
2012年11月12日晚上10:30:00
和(+0800 GMT)用户将$ item_date视为:
2012年11月13日下午06:30:00
我怎么做到的?谢谢
Dav*_*ler 23
这篇文章已经更新,包括一个完整的例子
<?php
session_start();
if (isset($_POST['timezone']))
{
$_SESSION['tz'] = $_POST['timezone'];
exit;
}
if (isset($_SESSION['tz']))
{
//at this point, you have the users timezone in your session
$item_date = 1371278212;
$dt = new DateTime();
$dt->setTimestamp($item_date);
//just for the fun: what would it be in UTC?
$dt->setTimezone(new DateTimeZone("UTC"));
$would_be = $dt->format('Y-m-d H:i:sP');
$dt->setTimezone(new DateTimeZone($_SESSION['tz']));
$is = $dt->format('Y-m-d H:i:sP');
echo "Timestamp " . $item_date . " is date " . $is .
" in users timezone " . $dt->getTimezone()->getName() .
" and would be " . $would_be . " in UTC<br />";
}
?>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jstimezonedetect/1.0.4/jstz.min.js"></script>
<script language="javascript">
$(document).ready(function() {
<?php if (!isset($_SESSION['tz'])) { ?>
$.ajax({
type: "POST",
url: "tz.php",
data: 'timezone=' + jstz.determine().name(),
success: function(data){
location.reload();
}
});
<?php } ?>
});
</script>
Run Code Online (Sandbox Code Playgroud)
我希望现在已经足够清楚了;).