• 0

[PHP] if date is in the next 30 days do something?


Question

Hi guys just a quick one that racking my brains.

in php I'm wanting to do a date comparison of two dates to see if they are in the next X days, but I only have "MM/DD" available to me,

so i tried the following code

.....
                     $fan = new Fan($this->fans[$i]);
                     $birthday = $fan->getBirthday()."/1900";
                     $dateNow = date("m/d")."/1900";

                     print ($birthday."----".$dateNow."<br/>");
                     print($this->dateDiff($dateNow,$birthday)  ."- difference";
                     if (($this->dateDiff($dateNow,$birthday) >= 30) && ($this->dateDiff($dateNow,$birthday) < 0))
                     {

                        print($this->dateDiff($dateNow,$birthday)  ."-got HERE");
                        $searchedFans->addFan($fan);
                     }
                     $i++;
                    }
......

    private function dateDiff($endDate, $beginDate)
    {
        $date_parts1=explode("/", $beginDate);
        $date_parts2=explode("/", $endDate);
        $start_date=gregoriantojd($date_parts1[1], $date_parts1[0], $date_parts1[2]);
        $end_date=gregoriantojd($date_parts2[1], $date_parts2[0], $date_parts2[2]);
        return $end_date - $start_date;
    }

but this only seems to be doing a monthly comparision instead of day

as i get the following output

  Quote
05/31/1900----02/20/1900

3 -difference

12/31/1900----02/20/1900

10 -difference

08/02/1900----02/20/1900

6 -difference

11/25/1900----02/20/1900

9 -difference

12/31/1900----02/20/1900

10 -difference

does anyone know how I could do a correct comparison on days?

thanks matt

8 answers to this question

Recommended Posts

  • 0

PHP Is not a platform I use at all so I got this from the PHP website.

The code there gave this example.

Some stuff to help you get started: 

<?php 
// See what's inside 
$oDT = new DateTime(); 
var_dump($oDT); 
?> 

To do a date difference: 

<?php 
$oDT = new DateTime(); //Sets the object to now 
$oDTDiff = $oDT->diff(new DateTime('2009-08-18 00:00:01')); 
var_dump($oDTDiff); 
echo "Days of difference: ". $oDTDiff->days; 
?> 

http://us.php.net/manual/en/datetime.diff.php

Also, you might want to set the year to the current year for both dates and not "1900". Since you'll probably run into leap year issues at the very least that way...

  • 0

Try this...

<?php

function safestrtotime($strInput) {
    $iVal = -1;
    $yearSkew = 0;
    for ($i=1900; $i<=1969; $i++) {
        # Check for this year string in date
        $strYear = (string)$i;
        if (!(strpos($strInput, $strYear)===false)) {
            $replYear = $strYear;
            $yearSkew = 1970 - $i;
            $strInput = str_replace($strYear, "1970", $strInput);
        };
    };
    $iVal = strtotime($strInput);
    if ($yearSkew > 0) {
        $numSecs = (60 * 60 * 24 * 365 * $yearSkew);
        $iVal = $iVal - $numSecs;
        $numLeapYears = 0;        # Work out number of leap years in period
        for ($j=$replYear; $j<=1969; $j++) {
            $thisYear = $j;
            $isLeapYear = false;
            # Is div by 4?
            if (($thisYear % 4) == 0) {
                $isLeapYear = true;
            };
            # Is div by 100?
            if (($thisYear % 100) == 0) {
                $isLeapYear = false;
            };
            # Is div by 1000?
            if (($thisYear % 1000) == 0) {
                $isLeapYear = true;
            };
            if ($isLeapYear == true) {
                $numLeapYears++;
            };
        };
        $iVal = $iVal - (60 * 60 * 24 * $numLeapYears);
    };
    return($iVal);
};

$date1 = '05/31/2001';
$date2 = '02/21/2001';

$date1 = explode('/', $date1);
$date2 = explode('/', $date2);

$date1 = $date1[2] . '/' . $date1[0] . '/' . $date1[1];
$date2 = $date2[2] . '/' . $date2[0] . '/' . $date2[1];

$diff = safestrtotime($date1) - safestrtotime($date2);

$diff = $diff / (60 * 60 * 24);

echo $diff;

?>

You can read more about the function safestrtotime here Strtotime function does not work for dates before 1970 hence a new function safestrtotime.

  • 0

Oops, I forgot to quote the string in my previous answer. Can't edit it anymore. I doubt you'll be echoing it anyway though, so here is a more useful version.

$diff = round((strtotime($fan->getBirthday() . date('/Y')) - time()) / 86400); if ($diff < 0) $diff += 365;

  • Like 1
  • 0
  On 21/02/2010 at 00:36, Hot said:

Oops, I forgot to quote the string in my previous answer. Can't edit it anymore. I doubt you'll be echoing it anyway though, so here is a more useful version.

$diff = round((strtotime($fan->getBirthday() . date('/Y')) - time()) / 86400); if ($diff < 0) $diff += 365;

your a star that's it!! can't believe it was that easy :D thanks a lot.

also thanks to the others for the help!

  • 0

Sorry to bring this back up, but I have to note that there may be a bug where you add 365 days when dealing with leap years. Also, it's better to use ceil() here instead of round() since otherwise you'll already be subtracting one day at noon.

<?php
// Set some variables to keep frequently used items cached
$birthday = $fan->getBirthday(); $now = time(); $year = date('Y');
// Get the next birthday, that means adding a year when you've already had your birthday this year
if( ($date = strtotime($birthday . '/' . $year)) < $now ) {
	$date = strtotime($birthday . '/' . ++$year);
}
// Get the amount of days, rounded up and without possible negative sign
$diff = (int) ceil( ($date - $now) / 86400 );
?>

This code won't actually give you "0 days" until your birthday, it'll already count to your next birthday on your birthday. You can get around this by changing the if-condition and add one day as buffer. By doing this, you'll prevent the addition of an extra year.

if( ($date = strtotime($birthday . '/' . $year)) + 86400 < $now ) {

Because of the way ceil() works for negative numbers, you don't even need to change the actual difference calculation for this case. The only nasty thing that ceil() does is rounding numbers between -1 and 0 to -0 (note the negative sign), that's why I added a cast to integer to get rid of the sign. You could also achieve this by adding zero or by using the abs() function (multiplying by 1 doesn't seem to work apparently).

Unfortunately, you can't get much shorter than this. If you really want to, you could get it all on one single line but it would become very unreadable. Therefore, I suggest wrapping this in its own function (e.g. getDaysToBirthday($fan) ) to keep your code clean. ;)

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.