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

前端 未结 3 1787
终归单人心
终归单人心 2020-12-16 08:29

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 acco

相关标签:
3条回答
  • 2020-12-16 09:11

    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.

    0 讨论(0)
  • 2020-12-16 09:17

    Really you should not be hacking the timestamps themselves to change the date within, you should just be applying the timezone to the timestamp before presenting the formatted datestamp to the user.

    This is a modified version of Mike's code that should work for PHP 5 >= 5.2.0 as found on php.net

    // OO Code
    $st = 1170288000 //  a timestamp 
    $dt = new DateTime("@$st"); 
    $dt->setTimeZone(new DateTimeZone('America/New_York'));
    $adjusted_timestamp = $dt->format('U') + $dt->getOffset();
    echo ' Timestamp adjusted for America/New_York: ' . $adjusted_timestamp;
    
    // Procedural Code
    $st = 1170288000 //  a timestamp 
    $dt = date_create("@$st"); 
    date_timezone_set($dt, timezone_open('America/New_York'));
    $adjusted_timestamp = date_format($dt, 'U') + date_offset_get($dt);
    echo ' Timestamp adjusted for America/New_York: ' . $adjusted_timestamp;
    
    0 讨论(0)
  • 2020-12-16 09:22

    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;
    
    0 讨论(0)
提交回复
热议问题