Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In PHP, why does `new DateTime('2012')` give me today's date?

I’ve run across a somewhat peculiar behavior in PHP that has me scratching my head. I’m genuinely not sure if this is intended behavior, or a bug. I was hoping someone might explain why it behaves the way it does.

So, of course, PHP’s DateTime class is overall pretty good at parsing date strings in a variety of different formats:

echo (new DateTime('today'))->format('Y-m-d'); // Gives 2024-08-15
echo (new DateTime('2012-02-18'))->format('Y-m-d'); // Gives 2012-02-18
echo (new DateTime('2012-02'))->format('Y-m-d'); // Gives 2012-02-01
echo (new DateTime('5 may'))->format('Y-m-d'); // Gives 2024-05-05
echo (new DateTime('6 days ago'))->format('Y-m-d'); // Gives 2024-08-09

However, when passed only a year, for some reason it gives today’s date:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

echo (new DateTime('2012'))->format('Y-m-d'); // Gives 2024-08-15

At first, I thought that perhaps it just defaults to ‘now’ when passed an invalid date, or a date in an unexpected format, but that does not appear to be the case. All of the following throw errors:

echo (new DateTime('fart'))->format('Y-m-d');
echo (new DateTime('1'))->format('Y-m-d');
echo (new DateTime('last may'))->format('Y-m-d');
echo (new DateTime('2012-02-48'))->format('Y-m-d');

So, why does passing a bare year give today’s date? Based on PHP’s behavior on other cases, I would expect it to either return Jan 1 of the year in question, or to throw an error. But returning today’s date seems like a very weird choice.

(Note: I’m not looking for a way to get Jan 1 for an arbitrary year; I’m just curious why PHP is behaving this particular way.)

>Solution :

According to the notes in the datetime format documentation the year-only notation only works if a timestring is present, otherwise a 4 digit string is treated as HH MM. Relevant note is about halfway down the page.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading