Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find if a date is a valid date, and not greater than year 2038?

Tags:

date

php

I have a site where users provide some dates, but if they enter year like 12 april 2099, then the I get date in the past (1969). How do I check it and apply a default max safe date?

thank you.

like image 485
user187580 Avatar asked Apr 30 '10 15:04

user187580


1 Answers

Try the DateTime classes

$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 the timestamp instead of Integers. But Integers are limited by your platform's value for PHP_INT_MAX. You can test this with formatting the datetime with 'U' (for timestamp) and passing it to date():

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

Notice how DateTime returns the correct timestamp but date cannot work with it:

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
);
like image 173
Gordon Avatar answered Sep 19 '22 02:09

Gordon