This article explains how to add and subtract number of days from a specific date in PHP. In many cases we have to get date after or before a specified interval of days, months and years from current date or from any specified date.
Note : With PHP version >= 5.3, you can also use the object of DateTime class and its add method. DateTime class will be demonstrated on next blog.This article demonstrate the use of strtotime() function.
Below are some examples to demonstrate these cases :
1. Add two days to current date :
<?php
echo date('Y-m-d');
echo date('Y-m-d', strtotime("+2 days"));
?>
Output :
2015-12-23
2015-12-25
2. Get date after 2 weeks from current date
<?php
echo date('Y-m-d', strtotime("+2 weeks"));
?>
Output :2016-01-06
3. Get Date before 2 months from 2015-10-07
<?php
$date = '2015-10-07';
echo date('Y-m-d', strtotime($date. ' - 2 month'));
?>
Output :2015-08-07
4. Add one year on 2015-08-08
<?php
$date = '2015-08-08';
echo date('Y-m-d', strtotime($date. ' + 1 year'));
?>
Output : 2016-08-08
Similarly we can add or subtract hours, minutes and seconds.
Example :
<?php
$current_time = date("Y-m-d H:i:s");
echo "Current Time : "$current_time;echo "<br>";
echo "After 2 hours : ".date("Y-m-d H:i:s", strtotime('+2 hours'));echo "<br>";
echo "Before 30 minutes : ".date("Y-m-d H:i:s", strtotime('-30 minutes'));echo "<br>";
echo "After 10 seconds : ".date("Y-m-d H:i:s", strtotime('+10 seconds'));echo "<br>";
?>
Output :
Current Time : 2015-12-23 15:35:50
After 2 hours : 2015-12-23 17:35:50
Before 30 minutes : 2015-12-23 15:05:50
After 10 seconds : 2015-12-23 15:36:00
0 Comment(s)