4

The below code returns 1970 if the year is 2038 and correct year (2037) if it is altered as 2037. why?

$date = '28/05/2038';
$date = strtr($date, '/', '-');
$year = date('Y', strtotime($date));
echo $year;

I did some research and understood that the strtotime conversion returns 0, when the passed value is unsupported and hence this happens. But I dont understand how will it become unsupported if I change the date from '28/05/2038' to '28/05/2037'.

Akhil Mohandas
  • 202
  • 1
  • 10
  • 4
    https://en.wikipedia.org/wiki/Year_2038_problem ; tl;dr: PHP uses 32-bit seconds since epoch (1970-01-01), and in 2038 it runs out of seconds. – Amadan Nov 16 '18 at 03:59
  • http://sandbox.onlinephpfunctions.com/code/d14a15031707b4d86beaebb9d776e120af9fb8cd a quick test on an online service returns the correct answer: 2038. Check for Amadan's comment, the 2038 problem, on your current environment of course. Update: Problem is easily repeated on PHP versions below 5.2.16 – NicoBerrogorry Nov 16 '18 at 04:01
  • 3
    really no one should be using strtotime() when there is the [date\time](http://php.net/manual/en/class.datetime.php) class –  Nov 16 '18 at 04:01
  • `date()` and it's associates should be deprecated really. Use the class `DateTime` to deal with those problems. – Havenard Nov 16 '18 at 04:03
  • 3
    Sorry, should say 32-bit PHP there. If you're on 64-bit PHP, it works okay. See `PHP_INT_SIZE`. As other say, `DateTime` stores components separately and thus does not have this weakness. – Amadan Nov 16 '18 at 04:05

1 Answers1

0

It seems the problem is easily repeated for PHP versions below 5.2.16 even with even with PHP_INT_SIZE = 8. For that version and above the code executes correctly. Upgrading PHP to 5.2.16 should solve it. Only tested for PHP_INT_SIZE = 8 (64 bit)

Here you can check for yourself.

If you happen to be on PHP 5.2.0 or higher (but below 5.2.16) you can go for DateTime class as others suggested in the question's comments.

Note: Upgrading a service on a populated server may not be possible, not on work and not even on university courses. But if it happens to be possible, then you should test the proper version of PHP before upgrading. If it works, you should investigate why it has been fixed and at which point the functionality was added, googling PHP's bugtracker. Then suggest the change.

NicoBerrogorry
  • 446
  • 4
  • 15