Viewed   90 times

Looking to create a function that will do this in PHP.

I need to add a number of months to a date, but not exceed the last day of the month in doing so.

For example:

Add 1 month to January (1-28th), 2011, should produce February (1-28th), 2011.
Add 1 month to January 30th, 2011, should produce February 28th, 2011.
Add 3 months to January 31st, 2011, should produce April 30th, 2011.
Add 13 months to January 30th, 2011, should produce February 29th, 2012.
Add 1 month to October 31st, 2011, should produce November 30th, 2011.

If I use date addition in PHP, I get overruns:

Adding 1 month to January 30th, 2011, results in March 2nd, 2011.

My specification doesn't allow me to overrun into a new month.

What's the easiest method to accomplish this?

 Answers

2

You can compare the day of the month before and after you add 1 month. If it's not the same, you exceeded the next month.

function add($date_str, $months)
{
    $date = new DateTime($date_str);

    // We extract the day of the month as $start_day
    $start_day = $date->format('j');

    // We add 1 month to the given date
    $date->modify("+{$months} month");

    // We extract the day of the month again so we can compare
    $end_day = $date->format('j');

    if ($start_day != $end_day)
    {
        // The day of the month isn't the same anymore, so we correct the date
        $date->modify('last day of last month');
    }

    return $date;
}

$result = add('2011-01-28', 1);   // 2011-02-28
$result = add('2011-01-31', 3);   // 2011-04-30
$result = add('2011-01-30', 13);  // 2012-02-29
$result = add('2011-10-31', 1);   // 2011-11-30
$result = add('2011-12-30', 1);   // 2011-02-28
Sunday, September 18, 2022
2

t returns the number of days in the month of a given date (see the docs for date):

$a_date = "2009-11-23";
echo date("Y-m-t", strtotime($a_date));
Thursday, September 15, 2022
4

you need to escape the a and t as both have special meaning when used as formatting options in date()

echo date('M j at h:i a');

See it in action

Monday, October 17, 2022
 
sgohl
 
3

You don't need to change the php.ini file if you use date_default_timezone_set(). Just set it to the timezone you will be working in.

Something like this should go in a config file or on the page where you're working with dates (if it is only one page):

date_default_timezone_set('America/Los_Angeles');
Friday, December 23, 2022
 
1

<?php

$current_month = date('n');
$MONTHS = array();
for ($m=0; $m<12; $m++) {
  $display_month = $m + $current_month;
  $MONTHS[] = date('F',mktime(1,1,1,$display_month,1,date("Y")));
}
foreach ($MONTHS as $month) {
  echo "
    <a
      href="http://mydomain.com/".strtolower($month).""
      title="$month">$month</a><br />";
}
?>

Sunday, September 25, 2022
 
jjn
 
jjn
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :