codaniel
codaniel

Reputation: 5253

How do I get next occurrence of a certain day of the month

I am trying to get stripe to set a end_trial date on the next occurrence of whatever day of the month the user chooses. i.e. If today is the 16th and the user chooses the 15th I need the unix timestamp for the 15th of the next month. However if today was the 14th I need the timestamp for tomorrow.

I tried the solution found on this SO question Find the date for next 15th using php .

When i ran the code suggested in that question and substituted 15 for 31

$nextnth = mktime(0, 0, 0, date('n') + (date('j') >= 31), 31);

echo date('Y-m-d', $nextnth);

The result is 2013-03-03

I also tried this one Get the date of the next occurrence of the 18th .

The second one would actually give me 2013-03-31 when i ran it one 2013-1-31.

Both had unexpected results. Is february the problem? Any guidance will be much appreciated.

Upvotes: 2

Views: 1869

Answers (2)

Dylan
Dylan

Reputation: 412

Here is a way to do it.

function nextDate($userDay){      

  $today = date('d'); // today

  $target = date('Y-m-'.$userDay);  // target day

  if($today <= $userDay){

   $return = strtotime($target);

  }
  else{

   $thisMonth = date('m') + 1;
   $thisYear = date('Y');

   if($userDay >= 28 && $thisMonth == 2){
       $userDay = 28;
   }


   while(!checkdate($thisMonth,$userDay,$thisYear)){

     $thisMonth++;

     if($thisMonth == 13){

       $thisMonth = 1;
       $thisYear++;

     }

   }      

   $return = strtotime($thisYear.'-'.$thisMonth.'-'.$userDay);

  }

  return $return; 

}

// usage
echo date('Y-m-d',nextDate(29));

We get the user's choice and compare it today.

  • If today is less than or equal to user choice, we return the timestamp for this month.

  • If today is greater than user choice, we loop through dates, adding a month (or a year if it's $thisMonth hits 13). Once this date does exist again, we have our answer.

We check the dates using php's checkdate function, strtotime and date.

Upvotes: 3

mileusna
mileusna

Reputation: 672

I really don't understand the question completely. You can easily determine the date for next 30 days for example

$next_ts = time() + 30 * 86400; // add 30 days to current timestamp
$next = date('Y-m-d', $next_ts);   // format string as Y-m-d 
echo $next;

If that is not what you need, please explain the problem.

Upvotes: 0

Related Questions