php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #75087 DateTime::createFromFormat fails with float without fractional part
Submitted: 2017-08-17 16:56 UTC Modified: 2017-08-17 17:04 UTC
From: ronan dot giron at vigicorp dot fr Assigned:
Status: Not a bug Package: Date/time related
PHP Version: 7.1.8 OS:
Private report: No CVE-ID: None
 [2017-08-17 16:56 UTC] ronan dot giron at vigicorp dot fr
Description:
------------
\DateTime::createFromFormat('U.u', microtime(true))
returns false when no microseconds.

Test script:
---------------
// OK
var_dump(\DateTime::createFromFormat('U.u', 1502988140.0001));


// KO : false
var_dump(\DateTime::createFromFormat('U.u', 1502988140.0000));


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2017-08-17 17:04 UTC] kelunik@php.net
-Summary: microtime() with 0 microseconds return false +Summary: DateTime::createFromFormat fails with float without fractional part -Status: Open +Status: Not a bug -Operating System: Windows +Operating System:
 [2017-08-17 17:04 UTC] kelunik@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

This is expected. createFromFormat accepts a string. A float without fraction doesn't contain a dot when transformed to a string.

Just use var_dump(\DateTime::createFromFormat('u U', microtime())); instead, which always has a microsecond and second part.
 [2017-08-17 17:25 UTC] ronan dot giron at vigicorp dot fr
var_dump(\DateTime::createFromFormat('u U', microtime()));
return false too.

But i understand.
This solution works :
\DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', ''))
 [2017-08-17 20:31 UTC] kelunik@php.net
Right, forgot that microtime() returns the first part as stringified float.

If you just want the current time, you can also just use "new DateTime;", which defaults to "now" for the first parameter.

https://3v4l.org/sjhKP
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Wed Apr 24 14:01:30 2024 UTC