Reputation: 397
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']));
Upvotes: 2
Views: 11349
Reputation: 877
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"));
Upvotes: 1
Reputation: 219924
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');
Upvotes: 7
Reputation: 7446
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!
Upvotes: 2
Reputation: 152294
Try with:
$modificator = ' +1 year -1 day';
$renewalDate = date('d F Y', strtotime($rows['CoverStartDate'] . $modificator));
Upvotes: 3