php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #74681 createFromFormat incorrect behavior if no day provided
Submitted: 2017-05-31 15:14 UTC Modified: 2017-05-31 15:45 UTC
From: raul at reyes dot solutions Assigned:
Status: Not a bug Package: Date/time related
PHP Version: Irrelevant OS: Any
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: raul at reyes dot solutions
New email:
PHP Version: OS:

 

 [2017-05-31 15:14 UTC] raul at reyes dot solutions
Description:
------------
Seems to default all dates to 31. if trying to create February of 2018 for example it defaults to March 3rd. 

DateTime::createFromFormat('my',"0218")

sets the date to 2018-03-03. I would think the correct behavior is setting the date to 01 (or maybe the last day 't')

Test script:
---------------
$date = DateTime::createFromFormat('my',"0218");
echo $date->format('Y-m-t') . " when expecting 2018-02-01";

Expected result:
----------------
2018-02-01

Actual result:
--------------
2018-03-03

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2017-05-31 15:38 UTC] derick@php.net
-Status: Open +Status: Not a bug
 [2017-05-31 15:38 UTC] derick@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

By default, all the fields are prefilled in with the current year/month/day values.

So my with 0218 becomes "2017-02-31", which overflows to 2017-03-03. You can prevent this by using the ! format specifier before "my" or the "|" specifier behind the "my" to set all values to 1970-01-01 00:00:00 first:


<?php
var_dump(DateTime::createFromFormat('!my',"0218"));
var_dump(DateTime::createFromFormat('my|',"0218"));
?>

your "Actual result" is not "2018-03-03" btw, it's "2018-03-31" as "t" is the number of days in the month (3), which is 31.
 [2017-05-31 15:45 UTC] raul at reyes dot solutions
oops, meant to change the t to a d ... thanks for letting me know about ! and | modifiers,
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Wed Jul 02 13:01:34 2025 UTC