LinkShare  Referral  Program

New

Advertise ad Here
learn more
            PHP > date manipulation functions> add subtract days
Added on   06.09.09
Clicks     20297
Rating:   4.11   out of 5 from   9   raters      
         rate this page   
 Not rated yet.Be the first one to vote!!

iBuyOfficesupply.com Inc. There is not Comments for this Article,Be the first one
Ask any relevant question in the Comments or leave your valuable feed-back

printer  Print version of this article

star  Add it to your favourite!

mail email this page to a frend
LinkShare  Referral  Program

Date and time manipulation functions



 How to add or subtract  days to a date -




 

 

    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

    <?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, for complete formatting details, visit the PHP manual 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

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

    Try the example below

     Today date is  30-07-10
     Days to add/subtract  
     Your time zone  
     The format you want  
     Your new date is