Jump to content

Recommended Posts

I'm trying to figure out how many months there are between today and a future date.

 

I don't want to subtract time() from a futuredate as it will not be accurate for certain months.

 

I can't multiply 60 seconds x 60 minutes x 24 hours x 30 days, as some months have 28, 29 and 31 days.

 

For example from today to Feb 10, 2008 - the answer should be 3 months and not 89 days (which is less than 3 months)

 

Any help would be greatly appreciated.

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/81109-calulate-number-of-months-remaining/
Share on other sites

I am not an expert but I can give you an example perhaps you can build upon it

 


$curDate = mktime(0,0,0,date('m'), date('d'), date('Y'));
$futureDate = mktime(0,0,0,month,day,year);			

$numberofdays = round(($furDate - $curDate)/86400);

 

That will give you exactly the number of days until the event.  Which you can then further deduce the number of months until that date.

The following does, what I believe, is close to what you want. For testing, I generate a random date in the future.

 

<?php
$future = rand(1,12) . '/' . rand(1,28) . '/' . rand(2008,2010);   // generate a random date in the future
$fd = strtotime($future);
$nw = time();
$cur_month = date('F');
$num_months = 0;
for ($dt = $nw; $dt <= $fd; $dt += 86400)
        if (date('F',$dt) != $cur_month) {
                $num_months++;
                $cur_month = date('F',$dt);
        }
echo 'Number of months between now and ' . $future . ' is ' . $num_months . "<br>\n";
?>

 

Ken

Try this instead:

<?php
$future = rand(1,12) . '/' . rand(1,28) . '/' . rand(2008,2010);
$fd = strtotime($future);
$nw = time();
$num_months = 0;
while ($nw <= $fd) {
        $num_months++;
        $nw = strtotime('+1 month',$nw);
}
echo 'Number of months between now and ' . $future . ' is ' . $num_months . "<br>\n";
?>

 

Ken

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.