• 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

    • Read the book when it came out. Can't wait to watch it. 
    • Microsoft wants partners to promote Edge for Business by Usama Jawad Microsoft's partner program is an initiative that aims to provide a collaborative framework through which businesses can build solutions using Redmond technologies and sell them at scale to their own customers. It enables Microsoft to reach a wider audience while also offering a financial incentive to businesses looking to leverage cutting-edge technology. Now, the company has explicitly asked its partners to bundle Edge for Business in their security offerings. In a blog post titled "Better browser security starts with Microsoft Edge for Business—and you", Microsoft has urged solution vendors offering security implementations to include Edge for Business in their package. It is being pitched as a secure browser meant for enterprise use-cases, with the additional benefit being the AI features in tow. Microsoft has also boasted that the browser contains advanced management tools that can save IT admins time and reduce overall costs. In order to assist independent solution vendors (ISVs) in promoting Edge for Business to more customers, Microsoft has actually prepared some resources to facilitate the process. This includes a collection of videos designed to emphasize the importance of protection against browser-based attacks. It has also packaged some demos for Edge management service (EMS) and Microsoft 365 Lighthouse. In fact, there's even a pitch deck, à la Apple, that can help partners emphasize the benefits of Edge for Business, along with a comprehensive landing page for the browser. This landing page contains information about how organizations can improve their security posture to protect themselves against cyberattacks, along with a white paper on cybersecurity and a licensing matrix. Even though some may view the move as desperate, there really is no downside to it. ISVs aren't being forced to promote Edge for Business to their own customers; Microsoft is just nudging them in that direction while offering some in-house assistance. As long as Edge for Business reaches more customers, it's a win-win situation for both Microsoft and its partners.
    • Well... that's one way to voice your insecurities I guess.
    • Im not sure how I feel about most of the trailing being about earth stuff, when none of the book takes place there, but the Rocky bits look cool!, I've been excited for this, and honestly surprised that Artimes never got a movie.
    • Here are all the new features Microsoft added to Teams in June 2025 by Usama Jawad Microsoft Teams is one of the most used software when it comes to online communication and collaboration, especially in enterprise environments. Even though there are still many features that people want in Teams, Microsoft tries to appease as many as it can with regular updates to the tool. Now, the Redmond tech firm has published a roundup of all the capabilities it added to Teams during the month of June 2025. Starting off with chat and collaboration improvements, we have an enhanced spellchecker offering support in up to three languages, with users being given the ability to add corrections to their personal dictionary too. In addition, the new chat and channels experience is now rolling out to Government Community Cloud (GCC) customers. Next, we have improvements to the meetings, webinars, and town halls experience. Loop-powered meeting notes are now available for GCC-High and Department of Defense (DoD) customers, and non-Teams users have the ability to join town hall meetings through Cloud Video Interoperability (CVI) join codes. It is also possible for those invited to join town halls and and webinars using sign-in details, such as PSTN. In a similar vein, town hall organizers can select individuals to manage the screen that is being shown to attendees. Organizers have more control over the broadcast of notifications too, and can also pull in a participant into the call directly and have them present their screen seamlessly. Lastly, town hall usage reports are now available in Teams Admin Center for additional insights. For those more interested on the hardware side of things, the following devices are now Teams-certified: Yealink MeetingBoard Pro MTRA Series-65, 75, and 86 inch Logitech 4K Pro Webcam (for consumer) Logitech Brio Ultra HD Pro Business Webcam (for business) Yealink RoomPanel E2 (8-inch) and E2 Plus (10 inch) Logitech Rally Board 65 + Tap IP for Teams Rooms on Android (wireless) Crestron Videobar 70 EPOS ADAPT 660 USB-C PolyStudio V12 Logitech Zone 305 (with native Bluetooth) That's not all, though. There are several other enhancements present across frontline worker solutions, security, and Teams Phone and Rooms. Read about them in detail here.
  • Recent Achievements

    • Week One Done
      dennis Nebeker earned a badge
      Week One Done
    • One Year In
      timothytoots earned a badge
      One Year In
    • One Month Later
      CHUNWEI earned a badge
      One Month Later
    • Week One Done
      TIGOSS earned a badge
      Week One Done
    • First Post
      henryj earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      466
    2. 2
      +FloatingFatMan
      194
    3. 3
      ATLien_0
      163
    4. 4
      Xenon
      78
    5. 5
      Som
      73
  • Tell a friend

    Love Neowin? Tell a friend!