Monday, December 24, 2007

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

    ListDeleteAt

    The ListDeleteAt function is a neat little coldfusion function and works just as well in PHP. This function is good for removing counted values from lists. I use it a lot in conjunction with other list functions.
    The Function:

    <php
    function ListDeleteAt($list,$position,$delimiter)
    {
    $delimiter = substr($delimiter, 1);
    $a = explode($delimiter,$list);
    for($i=0;$i<count($a);$i++)

    {
    if($i != $position)
    {
    if(! isset($return))
    {
    $return = $a[$i];
    }
    else
    {
    $return .= $delimiter . $a[$i];
    }
    }
    }
    return $return;
    }
    ?>

    Usage:

    To use the ListDeleteAt function with the default delimiter ',':

    <php
    $list = "a,b,c,d,e,f,g";

    $position = 3;
    echo ListDeleteAt($list,$position);
    ?>
    The Result: a,b,d,e,f,g. The 'c' which was in the third position has noe been removed!

    To use the ListDeleteAt function with a custom delimiter:

    <php
    $list = "12345";

    $position = 2;
    echo ListDeleteAt($list,$position);
    ?>

    The Result: '1345'. The '2' which was in the second position has noe been removed!

    Saturday, December 22, 2007

    ListContains

    The ListContains function is a quick and easy function to use. The ListContains function determines the index of the first list element that contains the specified substring. If the substring can not be found in the list, The ListContains function will returns zero. This function will not ignore empty sets; thus the list "a,b,c,,,d" has 8 elements
     
    The Function:
    <php
    function ListContains($list,$substring,$delimiter=",")
    {
        $delimiter = substr($delimiter,1);
        $a = explode($list,$delimiter);
        $return = 0;
        for($i=0;$i< count($a);$i++)
        {
            if(strstr($a[$i],$substring))
            {
                $return = $i + 1;
            }
        }
        return $return;
    }

    ?>
    Usage:
    Using the ListContains function is simple:
     
    <?php
        $list = "one,two,three";
        $substr = "two"
        if(ListContains($list,$substr) > 0)
        {
            echo $substr . " found at position " . ListContains($list,$substr):
        }
    ?>

    The output of this function will be: two found at position 2

    ListAppend

    ListAppend is a rather simple utility function, however when you are dealing with lists, it can prove a great ally. This is a function that I pulled out of a class of list functions. I will publish the entire class once I get the individual functions published. The default delimiter for the ListAppend function is a ','. The delimiter length should be 1 character. Regardless of the size of the delimiter, the function will only use the first character.

    The Function:

    <php

    function ListAppend($list,$value,$delimiter= ",")
    {
    $delimiter = substr($delimiter,1);
    $nList = $list . $delimiter . $value;
    return $nList;
    }

    ?>

    Usage:
    StatementOutputComment
    ListAppend('elem1,elem2', '' )elem1,elem2,Appended element is empty; delimiter is last character in list; list length is 2.
    ListAppend('', 'elem1,elem2' )elem1,elem2List length is 2.
    ListAppend("one___two", "three", "___")"one___two_three"Inserted the first character of delimiters before "three."

    ListAppend works great to add values to a list. This function will default to a ',' for a delimiter!

    For Example:

    <?php
    $list = "abcd";
    $value = "Z";
    echo ListAppend($list,$value);
    ?>


    The results is 'abcd,Z'!

    By sending the correct delimiter through, in this case '':

    <?php
    $list = "abcd";
    $value = "Z" ;
    echo ListAppend($list,$value,"");
    ?>


    The results is 'abcdZ'!

    Wednesday, December 19, 2007

    DateDiff

    The DateDiff function has been another useful function in report building. It can be useful when trying to determine the average time for each stage of development in a project, or the amount of time that it took to complete.  I have used it enough in both php and ColdFusion applications.  I have found that using a consistent method of calculating dates is worth its weight in gold in the long run!
    Parameter Description
    datePart Optional. String. Precision of the comparison.
  • s Precise to the second (default)
  • n Precise to the minute
  • h Precise to the hour
  • d Precise to the day
  • m Precise to the month
  • yyyy Precise to the year
  • date1 Date/time object, in the range 100 AD–9999 AD.
    date2 Date/time object, in the range 100 AD–9999 AD.

    The Function

     <?php

     function DateDiff($datepart, $date1, $date2)
     {
      $a = explode(" " ,$date1);
      $b = explode("-",$a[0]);
      if(count($a) > 1)
      {
       $c = explode(":",$a[1]);
      } 
      else
      {
       $c = array();$c[ 0] = 0;$c[1] = 0;$c[2] = 0;
      }
      $a1 = explode (" ",$date2);
      $b1 = explode("-",$a1[0]);
      if(count($a1) > 1)
      {
       $c1 = explode(":",$a1[1]);
      } 
      else
      {
       $c1 = array();$c1[ 0] = 0;$c1[1] = 0;$c1[2] = 0;
      }
       switch($datepart)
      {
       case "n":
    // Minute
        $db= 60;break;
       case "h":
    // Hour
        $db= 60*60;break;
       case "d":
    // Day
        $db=(60*60)*24;break;
       case "w":
    // Weeks
        $db=((60*60)*24)* 7;break;
       case "m":
    // Month
        $db=ceil(((( 60*60)*24)*365)/12);break;
        case "yyyy": // Year
        $db=(((60*60)*24)* 365);break;
       default:
        $db=1;
      }
      $nDate1 = mktime($c[0],$c[ 1],$c[2],$b[1],$b[2],$b[0]);
      $nDate2 = mktime($c1[ 0],$c1[1],$c1[2],$b1[1],$b1[2],$b1[0]);
      
      $rDate = $nDate1 - $nDate2;
      
      $num = number_format(($rDate/$db),4);
      
      if($num < 0)
      {
        return $num * -1;
      }
      else
      {
       return $num;
      }
     }

    ?>

    Usage:
    This is a example of how to use the DateDiff Function:

    <?php
     
     $datepart = "s";
     $date1 = "2007-12-01 19:20:12" ;
     $date2 = "2007-11-15 11:45:39";
     echo DateDiff($datepart, $date1, $date2);

    ?>

    The result should be: 1,409,673!

    <?php
     
     $datepart = "yyyy";
     $date1 = "2007-12-01 19:20:12" ;
     $date2 = "2007-11-15 11:45:39";
     echo DateDiff($datepart, $date1, $date2);

    ?>

    The result should be: 0.0447!

     

    Tuesday, December 18, 2007

    DateCompare

    The DateCompare function has been a very useful tool when building reports. By default, this function will compare dates down to the second. With a little bit of tweaking, you can have it compare down to the nano second. By sending a datepart in, you can specify the level of percision that you want.
    Parameter Description
    date1 Date/time object, in the range 100 AD–9999 AD.
    date2 Date/time object, in the range 100 AD–9999 AD.
    datePart Optional. String. Precision of the comparison. s Precise to the second (default) n Precise to the minute h Precise to the hour d Precise to the day m Precise to the month yyyy Precise to the year

     

     <?php

        function DateCompare($date1, $date2=date("Y-m-d H:i:s"), $datepart)
        {
             $a = explode(" ",$date1);
             $b = explode("-",$a[ 0]);
             if(count($a) > 1)
             {
                  $c = explode(":",$a[ 1]);
             } 
             else
             {
                  $c = array();$c[0] = 0;$c[1] = 0;$c[2] = 0;
             }
             $a1 = explode(" ",$date2);
             $b1 = explode("-",$a1[0]);    
             if(count($a1) > 1)
             {
                $c1 = explode(":",$a1[1]);
              } 

              else
             {
                  $c1 = array();$c1[0] = 0;$c1[1] = 0;$c1[2] = 0;
             }
             switch($datepart)
             {
                  case "n": // Minute
                       $c[0] = 0;$c1[0] = 0;break;
                  case "h": // Hour
                       $c[0] = 0;$c[1] =0;$c1[0] = 0;$c1[1] = 0;break;
                 case "d": // Day
                       $c[ 0] = 0;$c[1] = 0;$c[2] = 0;$c1[ 0] = 0;$c1[1] = 0;$c1[2] = 0;break;
                   case "m": // Month
                       $c[0] = 0;$c[ 1] = 0;$c[2] = 0;$c1[0] = 0;$c1[ 1] = 0;$c1[2] = 0;$b[1] = 0;$b1[1] = 0;break;
                  case "yyyy": // Year
                       $c[ 0] = 0;$c[1] = 0;$c[2] = 0;$c1[0] = 0;$c1[1] = 0;$c1[2] = 0;$b[1] = 0;$b1[ 1] = 0;$b[2] = 0;$b1[3] = 0;break;
                   default:
                       $e = "mc2";
             }
             $nDate1 = mktime($c[0 ],$c[1],$c[2],$b[1],$b[2],$b[0]);
             $nDate2 = mktime($c1[0],$c1[1],$c1[2],$b1[1],$b1[2],$b1[0 ]);
             if($nDate1 < $nDate2)
             {
                  return -1;
             }
             elseif ($nDate1 > $nDate2)
             {
                  return 1;
             }
             else
             {
                   return 0;
             }
        }

    ?>
     

    Usage:
    Using the DateCompare function is easy.  If date 1 is greater than date 2, the function will return 1.  If date 1 is less than date 2, the function will return a -1.  If the two dates are equal, the function will return a 0.

    <?php
        $date1 = "2007-05-01 15:07:54" ;
        $date2 = "2007-06-07 02:41:22";
        if(DateCompare($date1,$date2) == 1)
        {
             echo "Date 1 is GREATER THAN Date 2";
        }
        elseif (DateCompare($date1,$date2) == -1)
        {
             echo "Date 1 is LESS THAN Date 2";
        }
        else
        {
            echo "Date 1 EQUALS Date 2" ;
        }
    ?>

    Sunday, December 16, 2007

    DateFormat

    The DateFormat function is another really useful function. This is most helpful when using a timestamp from a database. Generally, I use the 'datetime' format from MySQL and the 'smalldatetime' format when using MSSQL. The date is returned as '2007-01-01 00:00:00'. In PHP, the best way to use dates is the Unix timestamp. The Unix timestamp is the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT). So right now, the time is '2007-12-16 11:46:56', using Unix, the timestamp the time is '1197823616' or 1197823616 seconds since midnight January 1 1970. This function will still use the date formating as defined in the php function date(). You can check it out at php.net. One little problem with this function is that you are required to send a full date through.

    The Function:
    <?php
    function DateFormat($date,$format)
    {
    $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;
    }
    if(strtolower($format) == "short")
    {
    $dformat = "m/d/Y";
    $tformat = "H:i a";
    }
    elseif(strtolower($format) == "medium")
    {
    $dformat = "M d, Y";
    $tformat = "H:i:s a";
    }
    elseif(strtolower($format) == "long")
    {
    $dformat = "F d, Y";
    $tformat = "H:i:s a e";
    }
    elseif(strtolower($format) == "full")
    {
    $dformat = "l F d, Y";
    $tformat = "H:i:s a e";
    }
    if(isset($dformat) && isset($tformat))
    {
    $date = date($dformat,mktime($cdbit[0],$cdbit[1],$cdbit[2],$bdbit[1],$bdbit[2],$bdbit[0])) . " " . date($tformat,mktime($cdbit[0],$cdbit[1],$cdbit[2],$bdbit[1],$bdbit[2],$bdbit[0]));
    }
    else
    {
    $date = date($format,mktime($cdbit[0],$cdbit[1],$cdbit[2],$bdbit[1],$bdbit[2],$bdbit[0]));
    }
    return $date;
    }
    ?>


    Usage:

    <?php
    $date = "2007-05-19 13:51:22";
    // You can use either
    echo DateFormat($date,"F d, Y, g:i a");
    // Or you can use
    echo DateFormat($date,"long");

    ?>

    The resulting output is: May 19, 2007 1:51 pm



    ListGetAt

    ListGetAt is a really cool ColdFusion function. Is great for grabbing values from a comma separated list (or any other delimited list)! I use this function a lot instead of the explode function. They essentially do the same, but using this function removes 1 step. Instead of first exploding the then getting the value for your array key. For the seasoned PHP coder and everyone else, the position will always start at 1 NOT 0. Also, the default delimiter is a ','(comma).

    The Function:

    function ListGetAt($list,$position,$delimiter=",")
    {
    $bit = explode($delimiter,$list);
    return $bit[($position-1)];
    }

    Usage:

    Using the ListGetAt function is quite easy!

    <?php
    $list =
    "apples,oranges,grapes";
    echo ListGetAt($list,1);
    ?>


    The resulting out put would be: apples

    <?php
    $list = "apples+oranges+grapes";
    echo ListGetAt($list,2,"+");
    ?>

    The resulting out put would be: oranges



    First Post

    My name is Shiloh. I'm a programmer living in West Palm Beach working for a small magazine developing business and website applications. I primarily program in ColdFusion and C#. My first language was PHP which I still use extensively today. I have found that there are many usefully functions that are built into ColdFusion. PHP has some great built in functions, but they do not meet fully meet the needs of a business application developer. This is my first attempt to build a library of PHP functions that mimic the built in functions in ColdFusion. I have not built any error handling into any of the functions as of yet. They can be touchy if the required variables are not in the required formats.



    I would love to get any feedback you have. If you want, send an email to shiloh@cf2php.net!



    Cheers and happy programming!