1

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:

  • Win PHP 5.4
  • Linux PHP 5.3
  • Viper Codepad
2

1 Answer 1

4

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"
Sign up to request clarification or add additional context in comments.

2 Comments

Well that works for my use case. But out of curiosity, what if I wanted to only parse the month, and use the current year/day/time?
@Petah, that's what you are doing (with your original code). But there aren't 30 days in February, the second month, so it's advancing to the third month. The ! defaults to 1970-01-01 00:00:00, so it avoids that problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.