php / php-src

The PHP Interpreter
https://www.php.net
Other
38.08k stars 7.74k forks source link

DateTime::createFromFormat # separation doesn't allow a space #16280

Open DanAoS opened 3 days ago

DanAoS commented 3 days ago

Description

The following code:

<?php
var_dump( DateTime::createFromFormat( '!d#M#Y H#i' , '07 Oct 2024 11:47' ) );

Resulted in this output:

bool(false)

But I expected this output instead:

object(DateTime)#1 (3) {
  ["date"]=>
  string(26) "2024-10-07 11:47:00.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(13) "Europe/London"
}

From the PHP manual, the # should allow the following separation characters:

One of the following separation symbol: ;, :, /, ., ,, -, ( or )

This appears to include space, between . and -, but from the code above it doesn't parse the date string with a space. If I replace the format string with '!d M Y H#i ' it works as expected, so the : in the time is being handled by #, and the numeric parts fit the date format characters.

If I replace the spaces in the date string with - then it works as expected, so it's not anything else in the date string causing the issue.

var_dump( DateTime::createFromFormat( '!d#M#Y H#i' , '07-Oct-2024 11:47' ) );

object(DateTime)#1 (3) {
  ["date"]=>
  string(26) "2024-10-07 11:47:00.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(13) "Europe/London"
}

PHP Version

PHP 8.3.9

Operating System

Windows Server 2016 ( IIS using PHP binaries from http://windows.php.net )

cmb69 commented 3 days ago

The list is hardly readable in the docs; see the source:

https://github.com/php/doc-en/blob/4266e03897e77751a6cf7d15f9556c92124d8df3/reference/datetime/datetimeimmutable/createfromformat.xml#L306-L309

So, no, space is not supported.

DanAoS commented 2 days ago

The list is hardly readable in the docs; see the source:

https://github.com/php/doc-en/blob/4266e03897e77751a6cf7d15f9556c92124d8df3/reference/datetime/datetimeimmutable/createfromformat.xml#L306-L309

So, no, space is not supported.

Thank you for the quick reply. I see now, it's not a space between commas, it's a comma between commas where the space is just padding after the previous comma ... doh.

Would adding space be considered for a future version? It might be useful to avoid having to use multiple formats to check for valid user entries in form submissions for dates, as in my example spaces and hyphens are easily interchangeable without changing the meaning of the date.