Reputation: 37
I have a function in php that uses the date_create_from_format function to convert dates in format 'Ym' to datetime. It works correctly except in one case I found today and I cant find the problem. The situation is the following:
Current date: 07/31/2014.
$period value: '201409' (as the month I want to do some calc on)
$newDateCreated = date_create_from_format('Ym', $period);
This returns a new datetime created but with the value of 10/01/2014 instead of 09/01/2014
If instead of setting the value 201409 I put 201411 or 201408 the new datetime is created correctly.
The only solution I found to this was to replace
$newDateCreated = date_create_from_format('Ym', $period);
for
$newDateCreated = date_create_from_format('Ymd', $period.'01');
I believe that this have to be something with the day of the month but I cant find the real problem. Any ideas about this?
Thanks in advance.
Upvotes: 2
Views: 606
Reputation: 11836
As 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.
If format contains the character !, then portions of the generated time not provided in format, as well as values to the left-hand side of the !, will be set to corresponding values from the Unix epoch.
The Unix epoch is 1970-01-01 00:00:00 UTC.
Example
date_create_from_format('Ym', '201409');
// Tries '2014-09-31 15:59:45', but since that date doesn't exists
// that becomes '2014-10-01':
// object(DateTime)#62 (3) {
// ["date"] => string(19) "2014-10-01 15:59:45"
// ["timezone_type"] => int(3)
// ["timezone"] => string(16) "Europe/Amsterdam"
// }
date_create_from_format('!Ym', '201409');
// object(DateTime)#62 (3) {
// ["date"] => string(19) "2014-09-01 00:00:00"
// ["timezone_type"] => int(3)
// ["timezone"] => string(16) "Europe/Amsterdam"
// }
Upvotes: 5