Reputation: 1068
I am trying to solve a supposedly basic problem. I want to check that if the user has entered valid date. Valid date in our application is that of today or up to next 7 days. So any date within that range is valid. Any date in past or from 7th day upward from now will be considered as invalid.
I have written a small function to solve this:
function is_valid($d)
{
if( strtotime($d) < strtotime('+7 days') ) {
return true;
}
else return false;
}
Usage : is_valid('01-20-2015'); //M-D-Y
But this is always returning true.
What am I doing wrong?
Ahmar
Upvotes: 0
Views: 2253
Reputation: 27295
Its much easier to use the DateTime functions.
$yourDate = new \DateTime('01-20-2015');
// Set 00:00:00 if you want the aktual date remove the setTime line
$beginOfDay = new \DateTime();
$beginOfDay->setTime(0,0,0);
// Calculate future date
$futureDate = clone $beginOfDay;
$futureDate->modify('+7 days');
if($yourDate > $beginOfDay && $yourDate < $futureDate) {
// do something
}
Upvotes: 1
Reputation: 2668
As suggeested in the comments - you don't consider strtotime()
being unable to parse the date entered (invalid date format etc).
Try this code:
function is_valid($d)
{
if( strtotime($d) !== FALSE && strtotime($d) < strtotime('+7 days') ) {
return true;
}
return false;
}
Usage : is_valid('01-20-2015'); //M-D-Y
You should also have in mind, that strtotime
depends on server's timezone, as described in docs.
Upvotes: 1
Reputation: 856
strtotime
can not parse that date format. You need to be using YYYY-MM-DD
Use this test code for confirmation;
<?php
function is_valid($d) {
if (strtotime($d) < strtotime('+7 day')) {
return true;
}
else
return false;
}
var_dump(is_valid('2015-12-25'));
// Wrong format;
echo "Right: " . strtotime('2015-12-25') . "\n";
// Right format;
echo "Wrong: " . strtotime('01-20-2015') . "\n";
Can be seen here; http://codepad.org/iudWZKnz
Upvotes: 0