DateAdd

I do a lot of business application programming. Accounting deals a lot with dates so my first batch of functions will more than likely be Date and Numeric functions because I use them a lot. The DateAdd function is really useful when building reports. For those that are familiar with ColdFusion, I do not use a few of the defaults in the ColdFusion version of this function.
  • datepart:
    yyyy - Year
    m - Month
    d - Day
    ww - Week
    h - Hour
    n - Minute
    s - Second
    l - Millisecond
    • action:
      If you are adding, use "+" or "-" for subtraction
    • number:
      Number of units of datepart to add to date (positive,to get dates in the future; negative, to get dates in the past). Number must be an integer.
    • date
      Date/time object, in the range 100 AD–9999AD.
    The Function:
    <?php

    function DateAdd($datepart,$action,$number, $date)
    {

    $adbit = explode(" ",$date);
    $bdbit = explode("-",$adbit[0 ]);
    if(count($adbit) > 1)
    {
    $cdbit = explode(":",$adbit[1]);
    }
    else
    {

    $cdbit = array();
    $cdbit[0] = 0;
    $cdbit[1] = 0;
    $cdbit[2] = 0;
    }
    switch($datepart)
    {
    case "l":
    // Millisecond (Lower case 'L')
    $e = 60/1000;
    break;
    case "s":
    // Second
    $e = 1 ;
    break;
    case "n":
    // Minute
    $e = 60;
    break;
    case "h":
    // Hour
    $e = 60*60;
    break;
    case "ww":
    // Week
    $e = ((60*60)*24)*7;
    break;
    case "d":
    // Day
    $e = (( 60*60)*24);
    break;
    case "m":
    // Month
    $e = (((60* 60)*24)*365)/12;
    break;
    case "yyyy":
    // Year
    $e = (((60* 60)*24)*365);
    break;
    default:
    $e = "error";
    }
    if($e == "error")
    {
    return false;
    }
    $intTime = mktime($cdbit[0],$cdbit[1],$cdbit[ 2],$bdbit[1],$bdbit[2],$bdbit[0]);
    if($action == "+")
    {
    $nTime = $intTime + ($e * $number);
    }
    else
    {
    $nTime = $intTime - ($e * $number);
    }
    return date( "Y-m-d H:i:s",$nTime);
    }

    ?>

    Usage:

    The DateAdd function can be used to add or subtract a numeric value from a date. Below is an example of how to add 7 days.

    <?php

    // Add 7 days to May 19th
    $date = "2007-05-19 13:51:22";

    $action = "+";
    $units_to_add = 7;
    $datepart = "d";
    // 'd' For Days
    echo DateAdd($datepart,$action,$units_to_add,$date);
    ?>


    The output will be: 2007-05-26 13:51:22

    Below is an example of how to subtract 7 days.

    <?php

    // Subtract 7 days from May 19th
    $date = "2007-05-19 13:51:22";

    $action = "-";
    $units_to_add = 7;
    $datepart = "d";
    // 'd' For Days
    echo DateAdd($datepart,$action,$units_to_add,$date);
    ?>


    The output will be: 2007-05-12 13:51:22