Converting from UTC in PHP using a variable timezome
I store timestamps on my server using a simple timestamp in SQL. When I pull down that timestamp, I run it through the following 开发者_开发知识库function in order to format the time.
How do I add to the following function in order to convert $timestamp into whatever timezone the user is querying from?
// Returns the formatted time
function displayDate($timestamp)
{
$secAgo = time() - $timestamp;
// 1 day
if ($secAgo < 86400)
return date('h:i:A', $timestamp);
// 1 week
if ($secAgo < (86400 * 7))
return date('l', $timestamp);
// older than 1 week
return date('m/t/y', $timestamp);
}
If you have timezone name to change, you can use something like:
$date = new DateTime(date('Y-m-d H:i:s', $timestamp), new DateTimeZone('UTC'));
$date->setTimezone(new DateTimeZone('Asia/Vladivostok'));
return $date->format('m/t/y');
Where Asia/Vladivostok
is the user's custom timezone.
@zerkms's method is the best way to convert timestamps to any timezone.
But if you do that every time you need to display a time, it may have a significant performance hit because you're setting up and tearing down a timezone object every time. There's a convenient shortcut, if all the timestamps on the page are going to be in the same timezone. (Which is usually the case, because users don't change timezones in the middle of an HTTP request.)
Somewhere outside of the function, do:
date_default_timezone_set('America/New_York'); // or any other timezone
It's probably a good idea to tie this into one of your session management functions, so that the same user always gets the same timezone.
Once you do this, date()
will automatically start using the correct timezone, assuming that $timestamp
represents a Unix timestamp. It will also automatically correct for daylight saving time. So there's no need to change anything in that function.
Use timezone_identifiers_list() to retrieve a list of valid timezones.
精彩评论