Add hours to current date using php

This is one of the simple thing to add the hours and minutes and seconds to current time using php and its functions. To display the current date with time using php date function like below:

date("Y-m-d H:i:s");

The strtotime() function parses an English textual date time into a Unix timestamp. using this function you can add and subtract date from current date of any other date.



To Set the current date in some variable called as a startTime. 

$startTime = date("Y-m-d H:i:s");

Add hours and minutes and seconds to current time use below php code:

$add_date = date('Y-m-d H:i:s',strtotime('+5 hour +30 minutes +1 seconds',strtotime($startTime)));
echo $add_date; echo " : Added 5hours, 30min, 1sec in Current Time.<br />"; 

Add week and days to current time use below php code:

$add_date2 = date('Y-m-d H:i:s',strtotime('+1 week 3 days 7 hours 5 seconds',strtotime($startTime)));
echo $add_date2; echo " : Added +1 week 3 days 7 hours 5 seconds<br />"; 

subtract hours and minutes and seconds to current time use below php code:

$sub_date = date('Y-m-d H:i:s',strtotime('-5 hour -30 minutes -1 seconds',strtotime($startTime)));
echo $sub_date; echo " : Subtracted 5hours, 30min, 1sec in Current Time.<br />";

You can also find the day based on current time using php strtotime function. For example i given below to find next monday from current date and time and also find last sunday from current date. Below php code to find this.

$nxt_mon = date('Y-m-d H:i:s',strtotime('next Monday',strtotime($startTime)));
echo $nxt_mon; echo " : next Monday date<br />";

$last_sun = date('Y-m-d H:i:s',strtotime('last Sunday',strtotime($startTime)));
echo $last_sun; echo " : last Sunday date<br />";

Full code below:

<?php
$startTime = date("Y-m-d H:i:s");

$add_date = date('Y-m-d H:i:s',strtotime('+5 hour +30 minutes +1 seconds',strtotime($startTime)));

$add_date2 = date('Y-m-d H:i:s',strtotime('+1 week 3 days 7 hours 5 seconds',strtotime($startTime)));

$sub_date = date('Y-m-d H:i:s',strtotime('-5 hour -30 minutes -1 seconds',strtotime($startTime)));

$nxt_mon = date('Y-m-d H:i:s',strtotime('next Monday',strtotime($startTime)));

$last_sun = date('Y-m-d H:i:s',strtotime('last Sunday',strtotime($startTime)));


echo $startTime; echo " : This is Current Time<br /> ";
echo $add_date; echo " : Added 5hours, 30min, 1sec in Current Time.<br />"; 
echo $add_date2; echo " : Added +1 week 3 days 7 hours 5 seconds<br />"; 
echo $sub_date; echo " : Subtracted 5hours, 30min, 1sec in Current Time.<br />";
echo $nxt_mon; echo " : next Monday date<br />";
echo $last_sun; echo " : last Sunday date<br />";

?>

Post a Comment

0 Comments