I encountered a situation today where I needed to format a date which was far into the future (Anno Domini 2199). However, my standard approach of converting the string into a timestamp via strtotime and then formatting it with date produced weird results. In situations like this, it’s best to create a date object.
For example, I was trying to do something like the following. (Don’t ask why I was dealing with a date that far in the future).
$date = '2199-12-31T08:00:00.000-06:00';
echo date('g:i a', strtotime($date));
But this was spitting out a value of “6:00 pm”. It should display “8:00 am”.
Since strtotime converts a date into the number of seconds since the Unix epoch, the value I wanted to store in an integer exceeded PHP’s 32-bit signed capabilities (I’m sure glad I found this post explaining it). Apparently, using this method, you cannot calculate dates past the year 2038.
So, the solution lies in creating a DateTime object with date_create, and then formatting it with date_format:
$date = '2199-12-31T08:00:00.000-06:00';
$d = date_create($date);
echo date_format($d, 'g:i a');
Now, it’s really 8:00 am. :)