Req #75623 [Com]: DateTime::createFromTimestamp() method

From: Date: Mon, 04 Dec 2017 21:46:02 +0000
Subject: Req #75623 [Com]: DateTime::createFromTimestamp() method
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-212918@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=75623&edit=1 ID: 75623 Comment by: saifmsg at yahoo dot com Reported by: saifmsg at yahoo dot com Summary: DateTime::createFromTimestamp() method Status: Open Type: Feature/Change Request Package: Date/time related Operating System: Linux PHP Version: 7.1.12 Block user comment: N Private report: N New Comment: DateTime("@" . $timestamp) is just another way to type cast. I will be surprised if anybody is storing timestamp as string in a database. And as long as strict_types is enabled it does not make sense to treat it anything else, it really helps in validating input from $_GET/$_POST. You are right it is ubiquitous and that is why it is important. Previous Comments: ------------------------------------------------------------------------ [2017-12-04 16:52:18] requinix@php.net new DateTime("@" . $timestamp) ? strict_types as an argument only works as long as your value is an int. If it's a string, say from $_GET/POST or some database drivers, then it won't work and you're back to typecasting. That said, Unix timestamps are such a widespread concept that adding a factory method specifically for them could be worthwhile. ------------------------------------------------------------------------ [2017-12-04 16:42:36] saifmsg at yahoo dot com Description: ------------ There need to be an easy way to create DateTime object from unix timestamp when "declare(strict_types=1)" is set. The problem is "createFromFormat" expects second parameter to be a string and it forces it to be casted into string. There are other ways also but not quite simple (see the attached code). It would be simple and easy if there is a factory method: DateTime::createFromTimestamp(int $timestamp) This was requested before the release of "strict_types", original feature request: https://bugs.php.net/bug.php?id=43595 Test script: --------------- <?php declare(strict_types=1); // get timestmap as int from model // for test lets set the current time. $timestamp = time(); // Option: 1 $dateTime = DateTime::createFromFormat('U', (string)$timestamp); // Option: 2a $dateTime = new DateTime(); $dateTime->setTimestamp($timestamp); // Option: 2b $dateTime = (new DateTime())->setTimestamp($timestamp); // While it could have been simpler: // $dateTime = DateTime::createFromTimestamp($timestamp); ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=75623&edit=1

« previous php.bugs (#212918) next »