Petah
Petah

Reputation: 46060

PHP DateTime::createFromFormat not working

DateTime::createFromFormat doesn't appear to be working correctly, does anyone know a reason and/or how to fix it?

Given this code:

var_dump(DateTime::createFromFormat('m', '02')->format('m'));
var_dump(DateTime::createFromFormat('n', '2')->format('n'));

My expected output would be

02
2

However I actually get:

03
3

Example: http://codepad.viper-7.com/e4hns6

I've tested this on a multitude of servers including:

Upvotes: 1

Views: 2089

Answers (1)

Hamish
Hamish

Reputation: 23354

From the manual:

"If format does not contain the character ! then portions of the generated time which are not specified in format will be set to the current system time."

The following should work as expected:

var_dump(DateTime::createFromFormat('!m', '02')->format('m'));
var_dump(DateTime::createFromFormat('!n', '2')->format('n'));

# result:
string(2) "02"
string(1) "2"

Upvotes: 4

Related Questions