Articles: 843 | Categories: 148   
   
   
Home Articles Contact Us
 
 
 
 
Date and time manipulation (0 Comments)
Admin: Posted Date: March 3, 2010

In PHP, despite the big choice of functions, there is not a specific function to add an interval of time, that could be a day, hour, month or year to a given date, therefore we have to code something to do the job.

Date and time manipulation functions

In PHP, despite the big choice of functions, there is not a specific  function to add an interval of time, that could be a day, hour, month or year  to a given date, therefore we have to code something to do the job. In these series of  articles, I'll try to make some functions that could be useful for your applications.

The first one is how to Add or Subtract days to today's date. We assume that all the functions will be saved in a file called php_functions.php
function add_day($days,$time_zone,$format){
$zone=3600*$time_zone;
$new_time = time() + $zone + ($days * 24 * 60 * 60);
$new_date=gmdate($format, $new_time);
return $new_date;
}
?>

Let's start explaining the above function, as you can see ,it has 3 parameters,
$days is where you put positive numbers for adding and negative to subtract ,
$time_zone is your time zone that will be added to the GMT time plus day light saving in summer if you have it, $format is where you put the format you want the date to appear in your page.

$zone=3600*$time_zone; The variable $zone will hold the result of your time zone by 3600 which are the seconds in 1 hour

$newtime will hold  the timestamp resulting by adding time() with $zone aand the result of the parameter $days by the seconds in a day.

$new_date is the final step,  that, with the help of a PHP function gmdate will transform a timestamp in a normal date.

See the example below

include 'php_functions.php';
$days= 2;
$time_zone=8;
$format='d-m-Y';
$today=add_day($days,$time_zone,$format);
echo $today;
?>

 

 

 
 
Add a Comment:
 
(You must be signed in to comment on an article. Not a member? Click here to register)
   
Title:

Comments: