How to Add PHP Days Hours Minutes and Seconds to Datetime
Last Update : 12 Dec, 2022In this article, you will learn the simplest way to add days, minutes, hours, and seconds to time using PHP.
When you developed a dynamic webpage by using PHP programming language, sometimes, you need to add days, minutes, hours, and seconds to that page dynamically. Then you can use the PHP date() and strtotime() functions to easily increase or decrease time.
The following PHP code example shows to do the following works.
- Add days to datetime in PHP.
- Add hours to datetime in PHP.
- Add minutes to datetime in PHP.
- Add seconds to datetime in PHP.
<?php
$baseTime = date("Y-m-d H:i:s");
//display the base time
echo 'Base Time: '.$baseTime.'<br>';
//add 2 hour to time
$cenvertedTime = date('Y-m-d H:i:s',strtotime('+2 hour',strtotime($baseTime)));
//display the converted time
echo 'Converted Time (added 2 hour): '.$cenvertedTime.'<br>';
//add 2 hour and 20 minutes to time
$cenvertedTime = date('Y-m-d H:i:s',strtotime('+2 hour +20 minutes',strtotime($baseTime)));
//display the converted time
echo 'Converted Time (added 2 hour & 20 minutes): '.$cenvertedTime.'<br>';
//add 2 hour, 20 minutes and 30 seconds to time
$cenvertedTime = date('Y-m-d H:i:s',strtotime('+2 hour +20 minutes +30 seconds',strtotime($baseTime)));
//display the converted time
echo 'Converted Time (added 2 hour, 20 minutes & 30 seconds): '.$cenvertedTime.'<br>';
//add 2 day, 2 hour, 20 minutes and 30 seconds to time
$cenvertedTime = date('Y-m-d H:i:s',strtotime('+2 day +2 hour +20 minutes +30 seconds',strtotime($baseTime)));
//display the converted time
echo 'Converted Time (added 2 day, 2 hour, 20 minutes & 30 seconds): '.$cenvertedTime.'<br>';
?>
This program produces the following result -:
Base Time: 2022-12-12 02:46:03
Converted Time (added 2 hour): 2022-12-12 04:46:03
Converted Time (added 2 hour & 20 minutes): 2022-12-12 05:06:03
Converted Time (added 2 hour, 20 minutes & 30 seconds): 2022-12-12 05:06:33
Converted Time (added 2 day, 2 hour, 20 minutes & 30 seconds): 2022-12-14 05:06:33