PHP Program - how to add day, month, year in date in php?

how to add day, month, year in date using php ?

There are two method to add days, months and years in date by using built-in php functions as below.

  1. strtotime() :   it is used to convert an English textual date-time description to a UNIX timestamp.
    i.e date('Y-m-d', strtotime($date. ' + 2 days'));
  2. date_add() : The date_add() function is used to add days, months, years, hours, minutes and seconds.
    i.e date_add($date, interval);

 

 

Example :

<?php
$start_date = '2021-04-05 02:24:00';
// PHP program to add days to $start_date using strtotime() function
echo '<br/>Date before adding day : ' . $start_date;
$end_date = date('Y-m-d H:i:s', strtotime($start_date . ' +1 day'));
echo '<br/>Date after adding 1 day: ' . $end_date;
echo "<br>-----------------------------------------------------";
// PHP program to add months to $start_date using strtotime() function
echo '<br/>Date before adding month: ' . $start_date;
$end_date = date('Y-m-d H:i:s', strtotime($start_date . ' +1 month'));
echo '<br/>Date after adding 1 month: ' . $end_date;
echo "<br>-----------------------------------------------------";
// PHP program to add years to $start_date using strtotime() function
echo '<br/>Date before adding year: ' . $start_date;
$end_date = date('Y-m-d H:i:s', strtotime($start_date . ' +1 year'));
echo '<br/>Date after adding 1 year: ' . $end_date;

echo "<br>-----------------------------------------------------";
echo "<br/>PHP program to add day, month, year, hour randomly.";
for($ys=0;$ys<5;$ys++){
echo "<br>".date('d M Y h:i:s a', strtotime(date("Y-m-d h:i:s a")." +".rand(1,28)." days +".rand(1,12)." month -1 year +".rand(1,12)." hour"));
}

echo "<br>-----------------------------------------------------";
echo "<br/>PHP program to add day, month, year, hour using date_add() function .";
$start_date =date_create("2021-04-06"); ;
date_add($start_date , date_interval_create_from_date_string("5 days"));
echo '<br/>Date after adding 5 days: ' .date_format($start_date, "Y-m-d");
?>

Output :

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

96827