views:

217

answers:

2

Hi,

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)

Your help is appreciated

+1  A: 

UNIX timestamps are by definition in UTC, which means that all conversion should be done just prior to printing out rather than with actual timestamps.

How to do this however depends on how you're formatting them currently. I believe PHP has built-in timezone handling.

Joonas Trussmann
I found a few functions, but none of them convert the timestamp itself to a different timezone. I do a lot of operations on the timestamp from the database, so specifying the timezone over and over in every instance I output the time is a bit of an overwork.
KeyStroke
+1  A: 

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
$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.2
$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;
Mike
Thanks, but I get this error 'Call to undefined method DateTime::createfromformat()'. How come it says it's not defined?
KeyStroke
What version of PHP are you using?
Mike
This code probably requires PHP 5.3
John Conde
oh crap I have 5.2.8. Didn't realize that. Thanks man. :)
KeyStroke