|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #75623 DateTime::createFromTimestamp() method
Submitted: 2017-12-04 16:42 UTC Modified: 2017-12-04 16:52 UTC
From: saifmsg at yahoo dot com Assigned:
Status: Open Package: Date/time related
PHP Version: 7.1.12 OS: Linux
Private report: No CVE-ID: None
View Add Comment Developer Edit
Anyone can comment on a bug. Have a simpler test case? Does it work for you on a different platform? Let us know!
Just going to say 'Me too!'? Don't clutter the database with that please — but make sure to vote on the bug!
Your email address:
Solve the problem:
41 + 38 = ?
Subscribe to this entry?

 [2017-12-04 16:42 UTC] saifmsg at yahoo dot com
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:

Test script:

//    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();

//  Option: 2b
$dateTime   = (new DateTime())->setTimestamp($timestamp);

//  While it could have been simpler:
//  $dateTime   = DateTime::createFromTimestamp($timestamp);


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2017-12-04 16:52 UTC]
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 21:46 UTC] saifmsg at yahoo dot com
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.
PHP Copyright © 2001-2021 The PHP Group
All rights reserved.
Last updated: Wed Oct 27 08:03:36 2021 UTC