PHP时间戳日期到用户时区
发布时间:2020-12-13 13:02:03 所属栏目:PHP教程 来源:网络整理
导读:我将$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);} 服务器区域(UTC)之后的输出: 12
|
我将$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);
}
服务器区域(UTC)之后的输出:
但我希望它根据用户时区进行转换 示例:假设用户的时间是2012年11月13日上午07:00:00(格林威治标准时间0800),服务器时间是2012年11月12日下午11:00:00(UTC),$item_date的时间戳是2012年11月12日10 :30:00(UTC)所以 (UTC)用户将$item_date视为:
和(0800 GMT)用户将$item_date视为:
我怎么做到的?
这篇文章已经更新,包括一个完整的例子
<?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>
我希望现在已经足够清楚了;). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
