kramer65
kramer65

Reputation: 53943

PHP: how to create date before the Epoch (1970) using Date instead of DateTime?

In my PHP script I've got a function handling birthdays like so:

$dateTime = \DateTime::createFromFormat('U', $time);

The problem is that this returns false with negative $time numbers (i.e. dates before 1-1-1970). In the PHP docs there's a comment saying that indeed

Note that the U option does not support negative timestamps (before 1970). You have to use date for that.

I'm unsure of how to use Date to get the same result as DateTime::createFromFormat() gives though. Does anybody have a tip on how to do this?

Upvotes: 1

Views: 1269

Answers (1)

deceze
deceze

Reputation: 522480

If you just need to format a UNIX timestamp as a readable date, date is simple to use:

// make sure to date_default_timezome_set() the timezone you want to format it in
echo date('Y-m-d H:i:s', -12345);

If you want to create a DateTime instance from a negative UNIX timestamp, you can use this form of the regular constructor:

$datetime = new DateTime('@-12345');

Upvotes: 3

Related Questions