php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #79685 createFromFormat doesn't work easily with unpadded components
Submitted: 2020-06-10 09:02 UTC Modified: 2021-12-27 07:51 UTC
Votes:1
Avg. Score:4.0 ± 0.0
Reproduced:1 of 1 (100.0%)
Same Version:0 (0.0%)
Same OS:1 (100.0%)
From: contact at eslistavenga dot nl Assigned:
Status: Duplicate Package: Date/time related
PHP Version: 7.4.6 OS: Linux
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: contact at eslistavenga dot nl
New email:
PHP Version: OS:

 

 [2020-06-10 09:02 UTC] contact at eslistavenga dot nl
Description:
------------
When using the DateTime format ymdGis without any formatting, like hour/minute/second separator, the method will throw an error. See code example below. The method expects a leading 0, even tho the hour format 'G' was used and not 'H'

Test script:
---------------
<?php

//won't work
$date = DateTime::createFromFormat('ymdGis', '20061071018');

var_dump($date); //false
var_dump(DateTime::getLastErrors());

//will work
$date = DateTime::createFromFormat('ymdG-is', '2006107-1018');

var_dump($date); //DateTime::object
var_dump(DateTime::getLastErrors());

Expected result:
----------------
A valid DateTime object

Actual result:
--------------
false

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2020-06-10 11:21 UTC] requinix@php.net
-Summary: createFromFormat doesn't work with option G +Summary: createFromFormat doesn't work easily with unpadded components -Type: Bug +Type: Documentation Problem
 [2020-06-10 11:21 UTC] requinix@php.net
The docs should explain in a little more detail about how the parser tries to handle this sort of situation. As when happens with other date strings in PHP, 'G' will not match *only* 0-23 but will support anything up to 99 and then overflow the date if you go too high. When the docs say 1 or 2 digits, that means it will consume one digit at a minimum and then consume the next if it's a digit as well. It will *not* stop at one digit just because the digit was 3-9, *nor* will it backtrack if it matches '2' then 4-9.
So 'G' is taking '71' (which would result in overflow), thus leaving the 's' one digit short, causing the parsing to fail.

Moral of the story is that you should always use padded numbers in your computer-friendly date strings.
 [2021-12-27 07:51 UTC] requinix@php.net
-Status: Open +Status: Duplicate
 [2021-12-27 07:51 UTC] requinix@php.net
Closing in favor of https://github.com/php/php-src/issues/7834
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Wed Nov 13 06:01:32 2024 UTC