Help with comparing dates...

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
hayesb2
Forum Newbie
Posts: 1
Joined: Thu Jan 05, 2012 8:26 pm

Help with comparing dates...

Post by hayesb2 »

OK I have this block of code below that I found and it works fine, however needs a small tweak and being a PHP newbie I am not sure how to accomplish it...I'm sure its something simple.

It's just comparing the current date to see if it falls between a set of dates...except in the code below the $start and $endDate have hardcoded years in them...I need the years to reflect the current system date year. I tried adding a variable to capture the system year and then input them into the DateTime function but PHP did not like that.

I want to keep the hardcoded day and month, just not the year...the current code will break in 2013.

Can someone help show me the proper code to accomplish this?

Code: Select all

<?
$start = new DateTime('01-01-2012'); // DD-MM-YYYY
$endDate= new DateTime('02-28-2012'); // DD-MM-YYYY
$curdate = new DateTime(date('d-m-Y'));

if ($start <= $curdate && $curdate <= $endDate) {
    /*
    The message below will appear if the current date is between the start and
    endDate - used standards HTML to ensure that any code will not be
    escaped by PHP. You can use any code here to wish to execute for the
    date range.
    */
    ?>
    <p><strong><font color="#FF0000">The time is between 1/1/2012 and 1/28/2012</font></strong></p>
 <?php
 // don't forget this last bit, it ends the if statement!
}
?>
User avatar
twinedev
Forum Regular
Posts: 984
Joined: Tue Sep 28, 2010 11:41 am
Location: Columbus, Ohio

Re: Help with comparing dates...

Post by twinedev »

Code: Select all

<?php 
    $startDate = new DateTime('01-01-'.date('Y'));
    $endDate = new DateTime('02-28-'.date('Y'));
?>
Two things to note, the comments you are listing say to do DD-MM, yet looks like you are doing MM-DD , not sure if that matters, to be honest, I'm old school and rarely use DateTime class.

Also, what you echo out is that it is between 1/1/2012 and 1/28/2012, yet the code you are looking between 1/1 and 2/28 so one or the other needs adjusted

Lastly, if the intent is to check for all of January and February, then you should set $endDate to 03-01-YEAR and use :

Code: Select all

if ($start <= $curdate && $curDate < $endDate) { 
as hard coding 2/28 will miss a day on leap years (ie, this year you would miss Feb 29th)

-Greg

PS. Also if the code is just to check all of January and February each year:

Code: Select all

<?php
    $curMonth = date('m');
    if ($curMonth == 1 || $curMonth == 2) {
        // It is January or February...
    } 
?>
Post Reply