Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Datetime Object, And Years

By Frederic Bouchery

<?php
for ($y = 1900; $y < 2100; $y++) {
  if (new DateTime($y)->format('Y') != $y) {
      echo $y, ' ', (new DateTime($y))->format('c'), "
";
      }
}

In this code, 2 years are given to Datetime, and handed back. Yet, they return the same value: 2024.

Under the hood, PHP attempts to decode the number. Instead of recognizing a year, it recognizes an hour. And, by default, it set the rest of the date to today. Later, when the date is formatted, the year becomes 2024.

One piece of advice is to format the date to PHP’s liking, or use the createFromFormat() method, which uses a provided format to decode the string.

See Also

PHP Features

Last updated: 10 September 2026