How to add the number of days to the PHP date correctly

Date('d.m.Y', strtotime('10.08.2010') + 667 *86400);

This does not work correctly gives the answer 07.06.2012 and should be 03.08.2012

2 answers

You can use the well-known library Carbon

use Carbon\Carbon;

// К указанной дате добавить год и вывести в формате даты
echo Carbon::parse('10.08.2010')->addYears(1)->toDateString();

It is very flexible, you can add it via methods:

->addHours() // Часы
->addDays() // Дни
->addYears() // Года
// и т.д.

Documentation for the Carbon PHP library

 0
Author: Chaikin Evgenii, 2018-04-11 09:10:18

If we take into account the figures that you have given, then we can do this:

$date = new DateTime('10.08.2010');
$date->add(new DateInterval('P1Y359D'));
echo $date->format('d.m.Y');

The result will be the required date

03.08.2012

After a discussion with @Enikeyshchik decided to add a couple of points. My calculations, as you could understand, start from the date 10.08.2010 and end on the date specified at the end of the post 03.08.2012.

Another moment. Unfortunately, the author did not specify: we are talking about a specific date or there is a certain array with different dates, according to which the calculation is performed. In the latter In this case, the approach to generating the result based on the number of days + the original date is fundamentally incorrect, because there can be 366 days in a year. In this case, in my opinion, it is necessary to add "2 years" and already subtract 6 days from here.

 0
Author: Rustin, 2018-04-11 10:25:53