note 130280 added to datetimeimmutable.construct

From: Date: Sun, 04 May 2025 12:42:19 +0000
Subject: note 130280 added to datetimeimmutable.construct
Groups: php.notes 
Request: Send a blank email to php-notes+get-222125@lists.php.net to get a copy of this message
Working on a (REST) interface between JavaScript and a database needs to take care of the problem of the time zone info. In JavaScript JSON.stringify() will convert all dates to UTC. Makes sense. If we receive and decode this on in the PHP realm we should explicitly say so and altought null indicates the configured locale timezone although I do believe that more often than not no timezone is configured in PHP. So better be save than sorry and prevent you to miss your flight: <?php $jsonString = '{ "date": "2025-05-04T11:58:37.848Z" }'; $dateString = json_decode($jsonString, true)['date']; // will contain the date in UTC (Zulu) tz $d = new \DateTimeImmutable($dateString, new \DateTimeZone('UTC')); // interpreted as such $databaseZone = new \DateTimeZone("Europe/Zurich"); $d = $d->setTimeZone( $databaseZone ); // but our server is somewhere else var_dump($d); // Now we can store the date in our local database, which is blissfully unaware of timezones ?> ---- Server IP: 45.112.84.4 Probable Submitter: 80.90.5.137 (proxied: 83.97.87.43) ---- Manual Page -- https://php.net/manual/en/datetimeimmutable.construct.php Edit -- https://main.php.net/note/edit/130280 Del: integrated -- https://main.php.net/note/delete/130280/integrated Del: useless -- https://main.php.net/note/delete/130280/useless Del: bad code -- https://main.php.net/note/delete/130280/bad+code Del: spam -- https://main.php.net/note/delete/130280/spam Del: non-english -- https://main.php.net/note/delete/130280/non-english Del: in docs -- https://main.php.net/note/delete/130280/in+docs Del: other reasons-- https://main.php.net/note/delete/130280 Reject -- https://main.php.net/note/reject/130280 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#222125) next »