How to handle date lower than 1970 in MongoDB

2019-07-06 04:48发布

I have a document with a "birthday" field and this can also have a value lower that 01-01-1970. How can I handle this? E.g.

{....
    'birthday' => newMongoDate(strtotime('31/10/1968')),
 ....
}

This creates a "birthday" value: "1/1/1970 12:00:00 AM" (DateTime)

标签: php mongodb
3条回答
We Are One
2楼-- · 2019-07-06 05:29

What version of PHP are you running? I'm guessing PHP < 5.1 on windows? strtotime() should have a date range of Fri, 13 Dec 1901 20:45:54 GMT and Tue, 19 Jan 2038 03:14:07 GMT with PHP 5.1 and later.

For PHP 5.2 and greater you could use:

$date = new DateTime('1 Jan 1950');
echo $date->format('Y-m-d');

or,

$date = DateTime::createFromFormat('d M Y','1 Jan 1950');
echo $date->format('Y-m-d');
查看更多
在下西门庆
3楼-- · 2019-07-06 05:29

That is because the UNIX timestamp goes from 1970 ( http://php.net/manual/en/function.strtotime.php ) which is where strototime counts from. Even though strtotime can go from 1901 it is noted that:

The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 UTC to Tue, 19 Jan 2038 03:14:07 UTC. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer.) Additionally, not all platforms support negative timestamps, therefore your date range may be limited to no earlier than the Unix epoch. This means that e.g. dates prior to Jan 1, 1970 will not work on Windows, some Linux distributions, and a few other operating systems. PHP 5.1.0 and newer versions overcome this limitation though.

So it is highly likely you are running into the problem where your system simply does not support a date before the epoch.

You can do as @nick says and use DateTime() instead, more specifically its own timestamp function: http://www.php.net/manual/en/datetime.gettimestamp.php

查看更多
forever°为你锁心
4楼-- · 2019-07-06 05:49

Only option that i can think of is to use nested Date object something like

birth_date : {
  year : 1968,
  month : 10,
  day : 31
}

of Course there would be issues but this is the only option for windows users.

查看更多
登录 后发表回答