PHP:如何将服务器时间戳转换为用户的时区? [英] PHP: How do I convert a server timestamp to the user's timezone?

查看:355
本文介绍了PHP:如何将服务器时间戳转换为用户的时区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用"time()"功能在数据库中存储时间.但是,它使用的是服务器的时区,我希望每个用户都可以根据他们的时区(在其个人资料中设置)查看时间.

I'm currently storing times using the 'time()' function in the database. However, it's using the timezone of the server, and I'd like for each user to see the time according to their timezone (set in their profile).

如何进行时间戳转换? (我的意思是从时间戳到时间戳,而不是从可读时间开始)

How do I do the timestamp conversion? (and I mean from timestamp to timestamp, not to readable time)

推荐答案

正如Joonas所说,UNIX时间戳在定义上是UTC,但是如果您确实需要,可以将类似的东西一起模仿时区特定的时间戳. >

As Joonas said, UNIX timestamps are by definition UTC, but you could hack something like this together to mimic timezone-specific timestamps if you really need to:

// PHP 5.3 - OO Code
$timestamp = time();
echo 'Unix timestamp: ' . $timestamp;
$dt = DateTime::createFromFormat('U', $timestamp);
$dt->setTimeZone(new DateTimeZone('America/New_York'));
$adjusted_timestamp = $dt->format('U') + $dt->getOffset();
echo ' Timestamp adjusted for America/New_York: ' . $adjusted_timestamp;

// PHP 5.3 - Procedural Code
$timestamp = time();
echo 'Unix timestamp: ' . $timestamp;
$dt = date_create_from_format('U', $timestamp);
date_timezone_set($dt, new DateTimeZone('America/New_York'));
$adjusted_timestamp = date_format($dt, 'U') + date_offset_get($dt);
echo ' Timestamp adjusted for America/New_York: ' . $adjusted_timestamp;

这篇关于PHP:如何将服务器时间戳转换为用户的时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆