php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #80918 Create from format does'nt work for february
Submitted: 2021-03-30 11:55 UTC Modified: 2021-03-30 12:00 UTC
From: steven dot woelk at papendorf dot info Assigned:
Status: Not a bug Package: Date/time related
PHP Version: Irrelevant OS: Windows
Private report: No CVE-ID: None
 [2021-03-30 11:55 UTC] steven dot woelk at papendorf dot info
Description:
------------
---
From manual page: https://php.net/datetime.createfromformat
---

Consider a script with the following line:

$currentDate = \DateTime::createFromFormat('Y-m', $something);

Most time it will work but for 2021-02 for instance the returned value would be 2021-03-02 11:51:47.000000.

This is not a timestamp in february 2021.

Test script:
---------------
$currentDate = \DateTime::createFromFormat('Y-m', '2021-02');

Expected result:
----------------
$currentDate = \DateTime::createFromFormat('Y-m', '2021-02');

$currentDate->format('Y-m') === '2021-02'

Actual result:
--------------
$currentDate = \DateTime::createFromFormat('Y-m', '2021-02');

$currentDate->format('Y-m') === '2021-03'

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2021-03-30 12:00 UTC] derick@php.net
-Status: Open +Status: Not a bug
 [2021-03-30 12:00 UTC] derick@php.net
Sorry, but your problem does not imply a bug in PHP itself.  For a
list of more appropriate places to ask for help using PHP, please
visit http://www.php.net/support.php as this bug system is not the
appropriate forum for asking support questions.  Due to the volume
of reports we can not explain in detail here why your report is not
a bug.  The support channels will be able to provide an explanation
for you.

Thank you for your interest in PHP.

This is expected, albeit perhaps surprising.

By default, all the individual fields are filled in with the current date and time:

2021-03-30 11:51

The createFromFormat('Y-m') overrides the year and month, resulting in:

2021-02-30 11:51

Of course there is no february 30th, and PHP will overflow:

2021-03-02 11:51

If you don't want to pre-fill in the values with the current date/time, use the ! operator as you can read about at https://www.php.net/manual/en/datetime.createfromformat.php :

\DateTime::createFromFormat('!Y-m');
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Mon Apr 29 23:01:28 2024 UTC