|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #49779 Add support for microtime to DateTime object construction
Submitted: 2009-10-05 19:03 UTC Modified: 2016-10-05 20:14 UTC
Avg. Score:4.5 ± 0.7
Reproduced:20 of 21 (95.2%)
Same Version:12 (60.0%)
Same OS:8 (40.0%)
From: urkle at outoforder dot cc Assigned: derick (profile)
Status: Closed Package: Date/time related
PHP Version: 5.3.0 OS: CentOS 5
Private report: No CVE-ID: None
 [2009-10-05 19:03 UTC] urkle at outoforder dot cc
Currently the DateTime object construction accepts a strtotime type input only for setting the date on the object.  This means that when trying to get the current time WITH microseconds you have to do something like this..

$t = microtime(true);
$micro = sprintf("%06d",($t - floor($t)) * 1000000);
$d = new DateTime( date('Y-m-d H:i:s.'.$micro,$t) );

which is highly inefficient as we are converting a float into a string and then converting it from a string into the internal format for the DateTime object.

It would be really nice to have a constructor for the DateTime object that would accept a float argument (defaulting to NOW w/ microseconds)

Possible suggestions would be
factory method
$d = DateTime::TimeWithMicroseconds();

make the constructor accept a float
$d = new DateTime(microtime(true));

modify the setTimestamp method in PHP 5.3 to accept a float.
$d = new DateTime();


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2010-11-24 10:57 UTC]
-Package: Feature/Change Request +Package: Date/time related
 [2016-10-05 20:14 UTC]
-Status: Open +Status: Closed -Assigned To: +Assigned To: derick
 [2016-10-05 20:14 UTC]
The fix for this bug has been committed.

Snapshots of the sources are packaged every three hours; this change
will be in the next snapshot. You can grab the snapshot at

 For Windows:
Thank you for the report, and for helping us make PHP better.

From PHP 7.1.0 RC4, you can do:

new DateTime();
new DateTime::createFromFormat( "U.u", microtime( TRUE ) );
DateTime::setTime() now also accepts an extra 4th argument to set microseconds.

I know it's not *exactly* what you've asked for, but I consider this to be "good enough" for now.
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sat Jul 13 08:01:29 2024 UTC