Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

increment date by one month

Tags:

date

php

Let's say I have a date in the following format: 2010-12-11 (year-mon-day)

With PHP, I want to increment the date by one month, and I want the year to be automatically incremented, if necessary (i.e. incrementing from December 2012 to January 2013).

Regards.

like image 261
tarique Avatar asked May 20 '10 00:05

tarique


People also ask

How do you increase a date by 30 days in Excel?

In cell C1, type =A1+30, and then press RETURN . This formula adds 30 days to the date in cell A1. In cell D1, type =C1-15, and then press RETURN .

What is the formula for increment?

Formula Method The most obvious way to increment a number in Excel is to add a value to it. Start with any value in cell A1, and enter "=A1+1" in cell A2 to increment the starting value by one. Copy the formula in A2 down the rest of the column to continuously increment the preceding number.

How do you add incremental dates in Excel?

Filling a column or row with dates that increment by one day is very easy: Type the initial date in the first cell. Select the cell with the initial date and drag the fill handle (a small green square at the bottom-right corner) down or to the right.


2 Answers

$time = strtotime("2010.12.11"); $final = date("Y-m-d", strtotime("+1 month", $time));  // Finally you will have the date you're looking for. 
like image 129
Raphael Caixeta Avatar answered Oct 02 '22 06:10

Raphael Caixeta


I needed similar functionality, except for a monthly cycle (plus months, minus 1 day). After searching S.O. for a while, I was able to craft this plug-n-play solution:

function add_months($months, DateTime $dateObject)      {         $next = new DateTime($dateObject->format('Y-m-d'));         $next->modify('last day of +'.$months.' month');          if($dateObject->format('d') > $next->format('d')) {             return $dateObject->diff($next);         } else {             return new DateInterval('P'.$months.'M');         }     }  function endCycle($d1, $months)     {         $date = new DateTime($d1);          // call second function to add the months         $newDate = $date->add(add_months($months, $date));          // goes back 1 day from date, remove if you want same day of month         $newDate->sub(new DateInterval('P1D'));           //formats final date to Y-m-d form         $dateReturned = $newDate->format('Y-m-d');           return $dateReturned;     } 

Example:

$startDate = '2014-06-03'; // select date in Y-m-d format $nMonths = 1; // choose how many months you want to move ahead $final = endCycle($startDate, $nMonths); // output: 2014-07-02 
like image 25
Jason Avatar answered Oct 02 '22 05:10

Jason