Add 1 year to Date and minus 1 Day at the same time

10,485

Solution 1

DateTime() accounts for leap years:

// PHP 5.2+
$dt = new DateTime($rows['CoverStartDate']);
$dt->modify('+1 year');
$dt->modify('-1 day');
$renewalDate  = $dt->format('d F Y');

or:

// PHP 5.3+
$dt = new DateTime($rows['CoverStartDate']);
$dt->add(new DateInterval('P1Y'));
$dt->sub(new DateInterval('P1D'));
$renewalDate  = $dt->format('d F Y');

or:

// PHP 5.5+
$renewalDate = (new DateTime('04/09/2013'))->add(new DateInterval('P1Y'))
                                           ->sub(new DateInterval('P1D'))
                                           ->format('d F Y');

Solution 2

Try with:

$modificator = ' +1 year -1 day';
$renewalDate = date('d F Y', strtotime($rows['CoverStartDate'] . $modificator));

Solution 3

Take a look at what strtotime can do:

<?php
echo strtotime("now"), "\n";
echo strtotime("10 September 2000"), "\n";
echo strtotime("+1 day"), "\n";
echo strtotime("+1 week"), "\n";
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime("next Thursday"), "\n";
echo strtotime("last Monday"), "\n";
?>

(taken from the official PHP manual).

In your case:

$renewalDate = date('d F Y', strtotime($rows['CoverStartDate']));
$desiredDate = date('d F Y', strtotime("{$renewalDate} + 1 year - 1 day"));
echo $date;

The example I tried myself is :

$date = date("d F Y");
$date = strtotime("{$date} + 1 year - 1 day");
$date = date("d F Y",$date);
echo $date;

And outputs 03 September 2014, which is correct.

Hope this helps!

Solution 4

This subtracts a day from a year from today: today + 1 year - 1 day.

$yearMinusOneDay = Date("Y-m-d h:i:s", strtotime("now"." +1 Year "."-1 day"));

Share:
10,485
user974435
Author by

user974435

Updated on September 06, 2022

Comments

  • user974435
    user974435 over 1 year

    What is the best way of adding to existing date 1 year and removing 1 day. So if todays date is 04/09/2013 I would like to have new date 03/09/2014. There is as well issue every 4 years year got 366 days instead of 365 and of course it should change month if start date is 01/09/2013 then end date should be 31/08/2014. Please help. My date fields looks like that. i think so I have to do something with mktime or time ?

    $renewalDate = date('d F Y', strtotime($rows['CoverStartDate']));
    
    • Jason McCreary
      Jason McCreary over 10 years
      Does this come from a database, if so, which one?