• 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

    • Nothing inherently wrong, but why buy 2021 tech in 2025? Assuming you were aiming for 6-10 years of usage, better to buy something current.
    • I have begun using Windows 11 native passkey feature. i have four passkeys set up so far. Three work fine, One has never worked. I have removed it and recreated it several times, still no luck. Anyway, on the websites in which it works, it works geat. No more two 2FA.
    • No, because most people coming into the workforce are already familiar with either MS Office or Google Docs. You know, from schools. Also, OnlyOffice is Russian, which should be a nogo for almost any European government
    • XMedia Recode 3.6.1.3 by Razvan Serea XMedia Recode is a free video and audio converter. XMedia Recode supports nearly all audio and video codecs. With XMedia Recode you can easily convert nearly all film and music files in the format you want. Convert for countless devices, select the predefined profile (iPhone, iPad, iPod Touch, Android-Tablets, Sony PSP, Amazon Kindle, Smartphones Blackberry, Wii und DS, Cowon, Android, HTC, Xbox360, Samsung, LG). XMedia Recode converts: 3GP in AVI, 3GP in FLV, AC3 in MP3, AC3 in WAV, ASF in 3GP, ASF in FLV, ASF in MP4, AVI in FLV, AVI in 3GP, FLAC in MP3, FLAC in WMA, FLV in 3GP, FLV in Mp3, DVD in 3GP, DVD in AC3, DVD in AVI, DVD in MP3, DVD in MP4, DVD in MOV, DVD in SVCD, DVD in VCD, DVD in WMV, OGG in MP3, OGG in WMA, MPEG in AVI, MP2 in MP3, MP4 in FLV, MP4 in AVI, M4P in MP3, MOV in 3GP, MOV in AVI, MOV in FLV, WMA in MP3, WMV in FLV, WAV in MP3. Main functions of XMedia Recode: Extracts audio tracks from DVD, Blu-ray and video files Framework also freely selectable color (Padding) Drag-n-drop of video files directly on the encoder Selection display format (1: 1, 3:2, 4:3, 5:4, 5:6, 11:9,16: 9, 16:10, 2.21: 1) Zoom shot (none, type character box, media, Pan Scan, to screen) ''Direct Stream'' copies the audio stream or video stream into the target format 2-Pass-Encoding Volume correction Can change framerate, bit rate, resolution Can extract audio stream of most video formats Produce DVD copies for mobile phones, various mobile devices Edit Video: Color correction Video cut Cropping Denoise Delogo Deblocking De-interlacing Flip Image Start Time End Time Resolution Rotate Image Sepia Sharpness Padding Video fade in / fade out XMedia Recode 3.6.1.3 changelog: Update of ffmpeg AOM AV1 Codec: Added "Quantization" options Update of x264 (3221) Codec Update of the Italian language file Update of the Korean language file Fixed minor bugs Download: XMedia Recode 64-bit | Portable ~20.0 MB (Freeware) Download: XMedia Recode 32-bit | Portable Download: XMedia Recode for Windows XP SP3, Vista | Portable ~10.0 MB View: XMedia Recode Website | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • It's not a joke but I think it is pretty hilarious I was searching Fitch for a credit rating on a fund.   I found what Fitch had to say about the fund including this disclarimer.  LOL "This abstract may have been generated in whole or in part using artificial intelligence and is therefore subject to error and inaccuracy, including but not limited to, hallucination" No link posted for privacy reasons.       
  • Recent Achievements

    • Dedicated
      Cole Multipass earned a badge
      Dedicated
    • Week One Done
      Alexander 001 earned a badge
      Week One Done
    • Week One Done
      icecreamconesleeves earned a badge
      Week One Done
    • One Year In
      PAC0 earned a badge
      One Year In
    • One Month Later
      PAC0 earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      564
    2. 2
      +FloatingFatMan
      191
    3. 3
      ATLien_0
      187
    4. 4
      Skyfrog
      114
    5. 5
      Som
      109
  • Tell a friend

    Love Neowin? Tell a friend!