Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add 30 days to date [duplicate]

Tags:

Hello all i am trying to add 30 days to my date. I am using below coding.

<?php $next_due_date = date('05/06/2016', strtotime("+30 days")); echo $next_due_date; ?> 

But it is returning to "05/06/2016" only!

Please help me!

like image 960
Rahul Mukati Avatar asked Jun 06 '16 03:06

Rahul Mukati


People also ask

How do you add days to a date?

Press Ctrl+1 to launch the Format Cells dialog, and click the Number tab. Under Category, click Date, select the date format you want, and then click OK. The value in each of the cells should appear as a date instead of a serial number.


1 Answers

Do not use php's date() function, it's not as accurate as the below solution and furthermore it is unreliable in the future.

Use the DateTime class

<?php $date = new DateTime('2016-06-06'); // Y-m-d $date->add(new DateInterval('P30D')); echo $date->format('Y-m-d') . "\n"; ?> 

The reason you should avoid anything to do with UNIX timestamps (time(), date(), strtotime() etc) is that they will inevitably break in the year 2038 due to integer limitations.

The maximum value of an integer is 2147483647 which converts to Tuesday, 19 January 2038 03:14:07 so come this time; this minute; this second; everything breaks

Source

Another example of why I stick to using DateTime is that it's actually able to calculate months correctly regardless of what the current date is:

$now = strtotime('31 December 2019');  for ($i = 1; $i <= 6; $i++) {     echo date('d M y', strtotime('-' . $i .' month', $now)) . PHP_EOL; }  

You'd get the following sequence of dates:

31 December 31 November 31 October 31 September 31 August 31 July 31 June 

PHP conveniently recognises that three of these dates are illegal and converts them into its best guess, leaving you with:

01 Dec 19 31 Oct 19 01 Oct 19 31 Aug 19 31 Jul 19 01 Jul 19 
like image 124
zanderwar Avatar answered Oct 05 '22 11:10

zanderwar