How do I know if a date is a valid date and not more than 2038?

I have a site where users provide several dates, but if they enter a year, like April 12, 2099, then I get a date in the past (1969). How to check it and apply the maximum safe date by default?

Thank you.

+5
source share
2 answers

Try DateTimeclasses

$dt = new DateTime('2099-01-01');
$dt->setTime(23,59);
$dt->add(new DateInterval('P10D'));
echo $dt->format('Y-m-d H:i:s'); // 2099-01-11 23:59:00

Not sure what DateTime uses internally to store timestamps instead of integers. But integers are limited by the value of your platform for PHP_INT_MAX. You can verify this by formatting datetime with "U" (for the timestamp) and passing it to date():

echo date('Y-m-d H:i:s', $dt->format('U')); // 1962-12-06 17:30:44

, DateTime , date :

var_dump(
    $dt->format('U'),                           // 4071855540
    date('U', $dt->format('U')),                // -223111756
    PHP_INT_MAX,                                // 2147483647
    PHP_INT_MAX+1,                              // -2147483648
    date('Y-m-d H:i:s', PHP_INT_MAX),         // 2038-01-19 04:14:07
    date('Y-m-d H:i:s', PHP_INT_MAX+1)        // 1901-12-13 21:45:52
);
+5

mktime. Fri, 13 Dec 1901 20:45:54 GMT Tue, 19 Jan 2038 03:14:07 GMT, , false.

var_dump(mktime(0, 0, 0, 1, 19, 2038)); // int(2147472000) 
var_dump(mktime(0, 0, 0, 1, 20, 2038)); // bool(false)
0

All Articles