• 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.
  • Posts

    • Been happy with Windows 11 myself even since first release in 2021, sure it hasn't always been perfect, but nothing is per say.. Issues i did have was minor ones, which is normal with any OS really. I still use Windows 10 at times on my unsupported Gaming Laptop, and i find myself using the Windows 11 Desktop more. Eventually replacing Gaming Laptop with a Windows 11 Compatible one somehow, someway this year or possibly next year at the latest, but its gonna happen--(May save all my Bing reward points except the 1000 to have extended support for 10) then work on getting quality Replacement hard)
    • Geez, this is dumb. I use my laptop sometimes in the dark when doing astrophotography to control my astro-PC... this explains why I have to keep entering my PIN when logging back in. So stupid. I can't see the keyboard in the dark, and I can't have lights everywhere to light it up because everything is very light sensitive (including my eyes!).
    • Naturally. I don't care about brand loyalty at all as it's all about price/performance/reliability etc (even what RejZoR said below is a great point to). basically bang-for-the-buck. because at the end of the day... one wants the cheapest possible price to maintain a certain minimum level of performance (or thereabouts). because generally after a certain point with CPU and GPU's the price starts to sky rocket without that much difference in performance where it really matters. p.s. historically I have bought more Intel CPU's and NVIDIA GPU's but I have had some AMD CPU's and one AMD GPU.
    • Both of these companies as well as Qualcomm and Apple need competition. Otherwise, they just coast. I don't prefer macOS, though I like some of Apple's hardware, but if anyone needs competition, it is Apple. Their prices are already outrageous and they need to have a reason to produce good hardware and at least keep prices remotely reasonable. (It is criminal what they charge for RAM upgrades especially.) Qualcomm needs to push AMD and Intel not to be so sloppy with the performance/efficiency aspect. Granted, AMD has been doing quite well in this respect considering they are not an ARM architecture. I personally want to have more options that truly compete with Macbook Air and Macbook Pro's on the Windows side. It is difficult to achieve what Apple does since they control the entire stack and that is fundamentally different for Windows PCs other than maybe Microsoft Surface PCs.
  • Recent Achievements

    • Week One Done
      Hartej earned a badge
      Week One Done
    • One Year In
      TsunadeMama earned a badge
      One Year In
    • Week One Done
      shaheen earned a badge
      Week One Done
    • Dedicated
      Cole Multipass earned a badge
      Dedicated
    • Week One Done
      Alexander 001 earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      571
    2. 2
      ATLien_0
      182
    3. 3
      +FloatingFatMan
      182
    4. 4
      Skyfrog
      111
    5. 5
      Som
      106
  • Tell a friend

    Love Neowin? Tell a friend!