PHP is today between these dates (exclude year)

172 views Asked by At

I'm trying to do a simple if echo statement.

<?php if (time("mm-dd") > strtotime("11-01") && time("mm-dd") < strtotime("02-28"))echo 'stuff' ?>

Basically I want to echo something if today is either Nov, Dec, Jan, Feb. The code works if I use time() and the full year but I'd like to just compare the month, day. I think I have some silly syntax error that I just can't figure out. This code snippet is placed in the <head> of my html if that makes a difference. Little help. Thanks.


This is what I ended up with. Thanks!

<?php if ($today > '12-16' || $today < '01-08') echo 'yes' ?>

with $today = date("m-d")

2

There are 2 answers

0
Chris On
  1. Use the date function instead of time.
  2. Switch && to ||. No m-d date string will ever be both greater than 11-01 and less than 02-28.
  3. You probably want to use an inclusive comparison operator with November 1 and an exclusive one against March 1 to account for leap years.
  4. Instead of calling date() twice, why not assign the result to a variable?

Here it is all together:

$today = date('m-d');
if ($today >= '11-01' || $today < '03-01') { ... }
9
SOFe On

Consider using date checking the month only:

$month = (int) date("m");
$isMonthCorrect = $month === 11 || $month === 12 || $month === 1 || $month === 2;

Note the importance of (int). Integer comparisons are more reliable than string comparisons, even if they behave similarly.

Or if you want to check between two dates, to optimize performance, you should evaluate the dates into timestamps before putting them in code.

For example, you can use some websites for converting Unix timestamps. (Not gonna advertise any here, but you can search "Unix timestamp converter) You can also use php -r to get quick output:

php -r 'echo strtotime("2016-11-01 00:00:00");'
php -r 'echo strtotime("2017-02-01 00:00:00");'

Then you can use them like this:

$minimum = 1477958400; // from first command line
$maximum = 1485907200; // from second command line

$isInPeriod = $minimum <= time() && time() <= $maximum;

Keep in mind:

  1. time() always returns the current Unix timestamp, i.e. number of seconds since the Unix Epoch. Use strtotime for converting a string to time, and use date() to convert a timestamp to a string in a given format.
  2. Unix timestamp is always absolute. You can't convert a "month" into a Unix timestamp. You can only obtain the current Unix timestamp with time(), or get specific data from the timestamp using date().

References: