Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Is timezone data somehow embeded into Timestamps?

date_default_timezone_set("Asia/Singapore"); // UTC +8
$dt = new DateTime();
$dt->setTimestamp(DateTime::createFromFormat('u', gmdate('u'))->getTimestamp());
echo $dt->getTimezone()->getName(); // Asia/Singapore
echo $dt->format('d M Y H:i:s'); // Correct local time

$dt->setTimezone(new DateTimeZone('UTC'));
echo $dt->format('d M Y H:i:s'); // Correct UTC Time
die;

I am wondering if timestamps contain timezone data. On line 3 you see that I used gmdate() which should give me UTC/GMT time. But when I get the timezone & formatted datetime, they are in localtime. I didn't set timezones in my DateTime object yet, gave it a UTC timestamp. It somehow knew to convert to localtime. Which makes me wonder if Timezone data are included in timestamps

like image 259
Jiew Meng Avatar asked Feb 22 '26 12:02

Jiew Meng


1 Answers

setTimestamp accepts the timestamp in GMT 0 and you passed it in GMT, because of gmdate('u'). DateTime object takes your current timezone by default.

After that - you have properly set timestamp and current timezone, that is why DateTime object formats the date for Singapore.

Which makes me wonder if Timezone data are included in timestamps

No. Timestamp stores just amount of seconds since unix-epoch.

like image 188
zerkms Avatar answered Feb 24 '26 02:02

zerkms