Marlon
Marlon

Reputation: 111

Formatted dates in PHP IF statement

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?

Upvotes: 0

Views: 71

Answers (1)

Brogan
Brogan

Reputation: 748

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';
}

Upvotes: 2

Related Questions