KeyStroke KeyStroke - 6 months ago 19
PHP Question

PHP: How do I convert a server timestamp to the user's timezone?

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)

Answer

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;
Comments