How do I add a certain number of days to the current date in PHP?
I already got the current date with:
$today = date('y:m:d');
Just need to add x number of days to it
How do I add a certain number of days to the current date in PHP?
I already got the current date with:
$today = date('y:m:d');
Just need to add x number of days to it
php supports c style date functions. You can add or substract date-periods with English-language style phrases via the strtotime function. examples...
$Today=date('y:m:d');
// add 3 days to date
$NewDate=Date('y:m:d', strtotime('+3 days'));
// subtract 3 days from date
$NewDate=Date('y:m:d', strtotime('-3 days'));
// PHP returns last sunday's date
$NewDate=Date('y:m:d', strtotime('Last Sunday'));
// One week from last sunday
$NewDate=Date('y:m:d', strtotime('+7 days Last Sunday'));
or
<select id="date_list" class="form-control" style="width:100%;">
<?php
$max_dates = 15;
$countDates = 0;
while ($countDates < $max_dates) {
$NewDate=Date('F d, Y', strtotime("+".$countDates." days"));
echo "<option>" . $NewDate . "</option>";
$countDates += 1;
}
?>
The date_add() function should do what you want. In addition, check out the docs (unofficial, but the official ones are a bit sparse) for the DateTime object, it's much nicer to work with than the procedural functions in PHP.
Add 15 day to a select element (using "Alive to Die" suggestion)
<select id="date_list" class="form-control" style="width:100%;">
<?php
$max_dates = 15;
$countDates = 0;
while ($countDates < $max_dates) {
$NewDate=Date('F d, Y', strtotime("+".$countDates." days"));
echo "<option>" . $NewDate . "</option>";
$countDates += 1;
}
?>
$NewTime = mktime(date('G'), date('i'), date('s'), date('n'), date('j') + $DaysToAdd, date('Y'));
From mktime documentation:
mktime() is useful for doing date arithmetic and validation, as it will automatically calculate the correct value for out-of-range input.
The advantage of this method is that you can add or subtract any time interval (hours, minutes, seconds, days, months, or years) in an easy to read line of code.
Beware there is a tradeoff in performance, as this code is about 2.5x slower than strtotime("+1 day") due to all the calls to the date() function. Consider re-using those values if you are in a loop.
You can also use Object Oriented Programming (OOP) instead of procedural programming:
$fiveDays = new DateInterval('P5D');
$today = new DateTime();
$fiveDaysAgo = $today->sub(fiveDays); // or ->add(fiveDays); to add 5 days
Or with just one line of code:
$fiveDaysAgo = (new DateTime())->sub(new DateInterval('P5D'));