Reputation: 147
i need to check and give error if any of these criterion are true: the date selected by user is:
I am checking in this code
if((strtotime($_POST["sch_date"])<=strtotime(date("d/m/Y"))) OR (((strtotime(date("d/m/Y",strtotime("+1 year"))))-(strtotime($_POST["sch_date"])))/(60*60*24)<0))
but this give haphazard results meaning it shows error if the selected date is 2 days less than 1 year. Can someone please advice how to go about this?
Upvotes: 2
Views: 171
Reputation: 7447
Your attempt was pretty close, maybe just a little over-complicated, try this:
date_default_timezone_set('America/Los_Angeles'); // Set your timezone
// Assuming $_POST['sch_date'] is in the form 'd/m/Y'
$date = str_replace('/', '-', $_POST['sch_date']);
if (strtotime($date) <= strtotime('today') || strtotime($date) > strtotime('+ 1 year'))
echo "error";
Note: This assumes $date
is a date in some standard format - m/d/Y
or d-m-Y
or Y-m-d
etc., but not a datetime. See here for standard formats It will give an error if $date
is
today or any date before today, or if $date
is after 1 year from today.
To convert your non-standard d/m/y
, you need this, which has been added to the code above:
$date = str_replace('/', '-', $_POST['sch_date']);
Upvotes: 0
Reputation: 219844
Using DateTime()
makes this easy as they are comparable:
$dateSelected = DateTime::createFromFormat('d/m/Y', '18/04/2014'); // put your date here
$today = new DateTime();
$oneYearFromNow = new DateTime('+1 year');
if ($dateSelected <= $today && $dateSelected > $oneYearFromNow) {
// we're good
}
else {
// it's the end of the world!
}
Upvotes: 4