Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding days to specific day

Tags:

Many examples are about adding days to this day. But how to do it, if I have different starding day?

For example (Does not work):

$day='2010-01-23';  // add 7 days to the date above $NewDate= Date('$day', strtotime("+7 days")); echo $NewDate; 

Example above does not work. How should I change the starding day by putting something else in the place of Date?

like image 217
jsk Avatar asked Dec 17 '09 18:12

jsk


People also ask

How do you calculate adding days to a date?

Adding days to a date in Excel. The date can be entered in several ways: As a cell reference, e.g. =A2 + 10. Using the DATE(year, month, day) function, e.g. =DATE(2015, 5, 6) + 10.

What is the formula to add days in Excel?

Add or subtract days from a date Enter your due dates in column A. Enter the number of days to add or subtract in column B. You can enter a negative number to subtract days from your start date, and a positive number to add to your date. In cell C2, enter =A2+B2, and copy down as needed.

How do I automatically add days in Excel?

Auto fill a date series that increases by one dayEnter your initial date in the first cell. Click on the cell with the first date to select it, and then drag the fill handle across or down the cells where you want Excel to add dates.

How do I add 15 days to a date in Excel?

Type '=' and select the first cell of the column containing the dates you want to add days to (cell A2). Next, type '+' followed by the number of days you want to add. So, if you want to add 15 days, type '+15' in the same cell. This means, your cell H2 should have the formula =A2+15.


2 Answers

For a very basic fix based on your code:

$day='2010-01-23';  // add 7 days to the date above $NewDate = date('Y-m-d', strtotime($day . " +7 days")); echo $NewDate; 

If you are using PHP 5.3+, you can use the new DateTime libs which are very handy:

$day = '2010-01-23';  // add 7 days to the date above $NewDate = new DateTime($day); $NewDate->add(new DateInterval('P7D'); echo $NewDate->format('Y-m-d'); 

I've fully switched to using DateTime myself now as it's very powerful. You can also specify the timezone easily when instantiating, i.e. new DateTime($time, new DateTimeZone('UTC')). You can use the methods add() and sub() for changing the date with DateInterval objects. Here's documentation:

  • http://php.net/manual/en/class.datetime.php
  • http://php.net/manual/en/class.dateinterval.php
like image 56
Corey Ballou Avatar answered Oct 10 '22 14:10

Corey Ballou


$NewDate = date('Y-m-d', strtotime('+7 days', strtotime($day))); 
like image 25
antpaw Avatar answered Oct 10 '22 12:10

antpaw