PHP: How to convert server timestamp to user timezone?

I am currently storing time using the time () function in the database. However, it uses the serverโ€™s time zone, and I would like each user to see the time according to their time zone (set in their profile).

How to do timestamp conversion? (and I mean from a timestamp to a timestamp, not for human-readable time)

+2
source share
3 answers

As Joonas notes, UNIX timestamps are UTC by definition, but you could hack something like this together to simulate time-dependent 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;
+9

, , , .

, PHP 5 >= 5.2.0 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;
+2

UNIX UTC, , , .

, , , . , PHP .

+1

Source: https://habr.com/ru/post/1766677/


All Articles