tags:

views:

72

answers:

2

Hello,

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.

+4  A: 

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
);
Gordon
Which, to use more words, means "don't work with timestamps." :)
Pekka
Thanks Gordon, I am trying to get my head around this datetime class.
@user187580 in case you feel uncomfortable with classes, you can also use the procedural equivalents. For instance `date_create`, `date_format`, etc.
Gordon
A: 

You can use the mktime function. If its provided with a date from Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT it returns the # of seconds from epoch else it returns false.

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