Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PHP 8.1 - DateTime::createFromFormat returns false #8652

Closed
capsandiego opened this issue May 29, 2022 · 4 comments
Closed

PHP 8.1 - DateTime::createFromFormat returns false #8652

capsandiego opened this issue May 29, 2022 · 4 comments

Comments

@capsandiego
Copy link

Description

The following code (which works perfectly in PHP 8.0:

<?php
var_dump(DateTime::createFromFormat('z Y', '147 2022'));

Resulted in this output:

bool(false)

But I expected this output instead:

object(DateTime)#2 (3) {
  ["date"]=>
  string(26) "2022-05-28 15:36:32.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(16) "America/New_York"
}

The only way to make it work is to swap day of the year and year.

PHP Version

PHP 8.1.6

Operating System

Ubuntu Server 18.04

@capsandiego capsandiego changed the title PHP 8.1 - DateTime::createFromFormat return false PHP 8.1 - DateTime::createFromFormat returns false May 29, 2022
@iluuu1994
Copy link
Member

Note that this changed in PHP 8.0.10. https://3v4l.org/N2MlJ

The docs also match the behavior.

https://www.php.net/manual/en/datetime.createfromformat.php

format character Description Example parsable values
z The day of the year (starting from 0); must be preceded by Y or y. 0 through 365

Note the word "preceded", and flipping the modifiers does actually solve the issue.
https://3v4l.org/2tXJd

But I'm not sure if this is an accidental or wanted change. Maybe @derickr can clarify.

@capsandiego
Copy link
Author

You are absolutely right! Evidently I missed the 8.0.10 changes (and the docs which is very clear)
Many thanks for the quick response!

@iluuu1994
Copy link
Member

No problem. Let's keep it open until Derick responds just to make sure this is expected.

@iluuu1994 iluuu1994 reopened this May 29, 2022
@derickr
Copy link
Contributor

derickr commented May 30, 2022

This is expected. The parser works from left to right, and without knowing the year, you don't know whether for example 147 is either May 28 in 2022, or the also correct May 27 in leap years. The fix in 8.0.10 makes this now a hard requirement as per the documentation instead of sometimes giving you the wrong answer (As it would have used the current year, 2022, to calculate the 147th day there).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants