php - 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.




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);


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

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



     if($thisMonth == 13){

       $thisMonth = 1;



   $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.




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.

People are also looking for solutions to the problem: Zend Php Foreach Loop array


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.