I'm playing around with the DateTime functionality in PHP, and I've hit a stumbling block that I can't explain.
Given the following two pieces of code, I would expect that they would put out the same value (2001-01-01), but the second block of code instead outputs 1 year from the date that the code is run (so for today, 15-01-2016). How can I get the second code block to output the expected value?
$date = new DateTime('2001-01-01');
$date->add(new DateInterval('P1Y'));
$date->format('d-m-Y'); // 01-01-2000, works as expected.
$date = new DateTime();
$date->createFromFormat('Y-m-d', '2001-01-01');
$date->add(new DateInterval('P1Y'));
$date->format('d-m-Y'); // 15-01-2016, output not what is expected.
I'm using PHP 5.6.4 on OSX 10.10, installed using Homebrew.
First of i don't get the same output as you do:
01-01-2002
15-01-2016
The first example should be pretty clear, you create a DateTime Object and add 1 year to it so from 01-01-2001 it get's 01-01-2002
In the second on it's pretty easy too, you just forgot to assign the value from createFromFormat(), so the DateTime just uses the current date e.g. 15-01-2015 and adds 1 year.
So just change this:
$date->createFromFormat('Y-m-d', '2001-01-01');
to this:
$date = $date->createFromFormat('Y-m-d', '2001-01-01');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With