Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next month, same day in PHP

I have an "event" that needs to be scheduled the same day of every month.

Say you set the start date on the 1st May you should get the next events on the 1st of Jun, 1 Jul etc. The problem comes with a start date on the 31st (the next ones could be 30 or 28 depending on the month).

Considering that there are months with different numbers of days (28, 30, 31) depending on the month itself and the year... what would be an easy way to setup this?

Consider the following (and flawed) nextmonth function:

$events = array()

function nextmonth($date) {
   return $date+(60*60*24*30);
}
$curr = $start;
while($curr < $end) {
    $events[ = $curr;
    $curr = nextmonth($curr);
}

Edited to add: The problem for me is, simply enough, how to solve what the number of days of any given month is and thus get the next corresponding date.

like image 888
Guillermo Avatar asked Jun 05 '09 22:06

Guillermo


People also ask

How to Get next month same date in PHP?

$date = date("Y-m-01"); $newdate = strtotime ( '+1 month' , strtotime ( $date ) ) ; This way, you will be able to get the month and year of the next month without having a month skipped.

What does date () do in PHP?

The date/time functions allow you to get the date and time from the server where your PHP script runs. You can then use the date/time functions to format the date and time in several ways. Note: These functions depend on the locale settings of your server.


1 Answers

Update:

This will give you the number of days in given month:

echo date('t', $timestamp);

See: date()

Old answer:

I'm not sure about the algorithm you're thinking of but I believe this will help you:

echo date('d-M-y', strtotime('next month'));
like image 184
Ionuț G. Stan Avatar answered Sep 24 '22 20:09

Ionuț G. Stan