0

I'm using a short series of if/else if statements in PHP. Within those statements I'm checking a condition to see if it is a specific date such as the following:

    $timezone       = date_default_timezone_set('America/Chicago');
    $TheDate        = date("F j, Y, g:i a");
    if ($TheDate >= "March 30, 2016, 9:00 pm" && $TheDate <= "March 30, 2016, 9:59 pm") {
echo "this"
}

else if ($TheDate >= "April 1, 2016, 10:00 am" && $TheDate <= "April 1, 2016, 4:00 pm") {
echo "that"
}

I have no idea what is going on, but I cannot stretch the date out past the current hour, if I do, my else statement of echo "" shows.

For example, if I write a statement of IF the dates is >= March 30, 2016, 10:00 am AND less than or equal to March 30, 2016, 12:00 pm, this does not work, what I want displayed does not show up.

However, if I were to write >= March 30, 2016, 10:00 am AND less than or equal to March 30, 2016, 10:55 am, that does work.

Any idea how I can fix this?

1
  • 1
    either use unix timestamp or DateTime objects to make comparisons, not date strings Commented Mar 31, 2016 at 3:12

1 Answer 1

2

I think what you're looking for is strtotime.

<?php    
date_default_timezone_set('America/Chicago');

$TheDate = strtotime('March 30, 2016, 9:30 pm');

//$TheDate = strtotime(date('F j, Y, g:i a'));
//$TheDate = time(); // This is much better for getting the current unix timestamp.

if($TheDate >= strtotime('March 30, 2016, 9:00 pm') && $TheDate <= strtotime('March 30, 2016, 9:59 pm')) {
    echo 'this';
}
elseif($TheDate >= strtotime('April 1, 2016, 10:00 am') && $TheDate <= strtotime('April 1, 2016, 4:00 pm')) {
    echo 'that';
}
else {
    echo 'neither';
}
Sign up to request clarification or add additional context in comments.

4 Comments

The variable, 'strtotime('March 30, 2016, 9:30 pm'); does that represent just the formatting? What if in another else statement the month is different, or the year?
I left that there to show you that you can reverse the date function using strtotime, since you used the date function in your question.
strtotime returns a unix timestamp of the string its trying to interpret. Thats the number of seconds since the unix epoch, January 1st, 1970. The time function returns the current unix timestamp. See en.wikipedia.org/wiki/Unix_time
I found that I had to add an additional variable to the 'else if' statement in order for that condition to work. I had to use $TheDate2 = strtotime('April 1, 2016, 10:00 am'); the exact start time of that condition. Did I do something wrong? Should I only need one variable for the entire set of conditions?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.