简体   繁体   中英

PHP timestamps & timezone configuration

My plan:

  • Get the current timestamp using strtotime("now")
  • Convert that to timezone '0' - This is the part I don't know how to do. I have the number that represents the users timezone, like -8 hours for example.
  • Store it in the database in timezone '0'
  • Retrieve it from the database in timezone '0'
  • Convert it to the users timezone in the opposite direction
  • use the date('', timestamp) function to display it

How can I accomplish the conversion? Or am I going about this wrong?

I need to be able to store it in the database as a numerically represented time (like strtotime returns)

Using time() is the same as strtotime("now") and you do not need to worry about converting the timezone of the timestamp, as the timestamp has no timezone:

Does PHP time() return a GMT/UTC Timestamp?

time returns a UNIX timestamp, which is timezone independent. Since a UNIX timestamp denotes the seconds since 1970 UTC you could say it's UTC, but it really has no timezone.

You can then store that timestamp in your database. When you retrieve it you can convert it to the users timezone. With something like this:

date_default_timezone_set('UTC');

$timestamp = '1429066967';
//Supported Timezones: http://php.net/manual/en/timezones.php
$userTimezone = 'America/Los_Angeles';

$dt = new DateTime();
// Set the timestamp
$dt->setTimestamp($timestamp);
// Set the timezone
$dt->setTimezone(new DateTimeZone($userTimezone));
// Format the date
$date = $dt->format('Y-m-d H:i:s');

echo $date;

Outputs: 2015-04-14 20:02:47

But if you only have the UTC offset you could try this:

date_default_timezone_set('UTC');

$timestamp = '1429066967';
$offset = -8;
$userTimezone = timezone_name_from_abbr("", $offset*3600, false);


$dt = new DateTime();
// Set the timestamp
$dt->setTimestamp($timestamp);
// Set the timezone
$dt->setTimezone(new DateTimeZone($userTimezone));
// Format the date
$date = $dt->format('Y-m-d H:i:s');

echo $date;

Which also outputs: 2015-04-14 20:02:47

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM