note 126224 added to datetimeimmutable.createfrominterface

From: Date: Wed, 07 Jul 2021 11:12:00 +0000
Subject: note 126224 added to datetimeimmutable.createfrominterface
Groups: php.notes 
Request: Send a blank email to php-notes+get-216586@lists.php.net to get a copy of this message
php7 polyfill: <?php function PolyfillDateTimeImmutableCreateFromInterface(DateTimeInterface $dti):DateTimeImmutable{ $tz = $dti->getTimezone(); $ret = DateTimeImmutable::createFromFormat(DateTimeInterface::RFC3339, $dti->format(DateTimeInterface::RFC3339)); if(!!$tz){ // without this: timezone +01:00 // with this: timezone Europe/Oslo $ret = $ret->setTimezone($tz); } return $ret; } ?> testing it: <?php $dt = new DateTime("1970-01-01",timezone_open("Europe/Oslo")); $dti = PolyfillDateTimeImmutableCreateFromInterface($dt); var_dump($dti->format(DateTime::RFC3339), $dti->getTimezone()); die(); ?> gives: string(25) "1970-01-01T00:00:00+01:00" object(DateTimeZone)#2 (2) { ["timezone_type"]=> int(3) ["timezone"]=> string(11) "Europe/Oslo" } - and warning: using the TimeZone argument of the DateTimeImmutable constructor is a trap, in the example above if i used the constructor argument instead of setTimezone(), it would become "timezone_type=>1 timezone=>+01:00" instead of "timezone=>europe/oslo", the timezone name would be lost. ---- Server IP: 45.112.84.4 Probable Submitter: 45.112.85.242 (proxied: 84.48.255.36) ---- Manual Page -- https://php.net/manual/en/datetimeimmutable.createfrominterface.php Edit -- https://main.php.net/note/edit/126224 Del: integrated -- https://main.php.net/note/delete/126224/integrated Del: useless -- https://main.php.net/note/delete/126224/useless Del: bad code -- https://main.php.net/note/delete/126224/bad+code Del: spam -- https://main.php.net/note/delete/126224/spam Del: non-english -- https://main.php.net/note/delete/126224/non-english Del: in docs -- https://main.php.net/note/delete/126224/in+docs Del: other reasons-- https://main.php.net/note/delete/126224 Reject -- https://main.php.net/note/reject/126224 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#216586) next »