How to add 1 month on a date without skipping i.e. february

datetime, php

Solution

It seems that there is no ready function for it, so I wrote it by myself. This should solve my problem. Thanks anyway for your answers and comments. If you will find some errors, please provide in the comments.

This function calculates the month and the year I will end in after adding some month. Then it checks if the date is right. If not, we have the case that the day is not in the target month, so we take the last day in the month instead. Tested with PHP 5.3.10.

<?php
$monthToAdd = 1;

$d1 = DateTime::createFromFormat('Y-m-d H:i:s', '2011-01-30 15:57:57');

$year = $d1->format('Y');
$month = $d1->format('n');
$day = $d1->format('d');

$year += floor($monthToAdd/12);
$monthToAdd = $monthToAdd%12;
$month += $monthToAdd;
if($month > 12) {
    $year ++;
    $month = $month % 12;
    if($month === 0)
        $month = 12;
}

if(!checkdate($month, $day, $year)) {
    $d2 = DateTime::createFromFormat('Y-n-j', $year.'-'.$month.'-1');
    $d2->modify('last day of');
}else {
    $d2 = DateTime::createFromFormat('Y-n-d', $year.'-'.$month.'-'.$day);
}
$d2->setTime($d1->format('H'), $d1->format('i'), $d1->format('s'));
echo $d2->format('Y-m-d H:i:s');

Problem

Possible Duplicate: PHP DateTime::modify adding and subtracting months I have a starting date (i.e. 2011-01-30) and want to add 1 month. The problem is in defining what a month is. So if I use the following code: ``` $d1 = DateTime::createFromFormat('Y-m-d H:i:s', '2011-01-30 15:57:57'); $d1->add(new DateInterval('P1M')); echo $d1->format('Y-m-d H:i:s'); ``` I get the following result: 2011-03-02 15:57:57 The problem is, that I need it to use the following rules: - If I add 1 month it will just add 1 on the month part and leave the day part (2011-01-15 will become 2011-02-15) - If the day is not existing in the month we will end, we take the last existing day of it (2011-01-30 will become 2011-02-28) Is there a common function in php that can do this or do I have to code it by myself? Maybe I'm just missing a parameter or something!?

Original source

Related problems