Source for file date_functions.php

Documentation is available at date_functions.php

  1. <?php
  2. /**
  3.  * CodeIgniter
  4.  *
  5.  * An open source application development framework for PHP 4.3.2 or newer
  6.  *
  7.  * @package        CodeIgniter
  8.  * @subpackage     Helpers
  9.  * @author        ExpressionEngine Dev Team
  10.  * @copyright    Copyright (c) 2006, EllisLab, Inc.
  11.  * @license        http://codeigniter.com/user_guide/license.html
  12.  * @link        http://codeigniter.com
  13.  * @since        Version 1.0
  14.  * @filesource
  15.  */
  16.  
  17. // ------------------------------------------------------------------------
  18.  
  19. /**
  20.  * CodeIgniter Date Helpers
  21.  *
  22.  * @author        ExpressionEngine Dev Team
  23.  * @link        http://codeigniter.com/user_guide/helpers/date_helper.html
  24.  */
  25.  
  26. // ------------------------------------------------------------------------
  27.  
  28. if (function_exists('mdate')) {
  29.     /**
  30.      * Convert MySQL Style Datecodes
  31.      *
  32.      * This function is identical to PHPs date() function,
  33.      * except that it allows date codes to be formatted using
  34.      * the MySQL style, where each code letter is preceded
  35.      * with a percent sign:  %Y %m %d etc...
  36.      *
  37.      * The benefit of doing dates this way is that you don't
  38.      * have to worry about escaping your text letters that
  39.      * match the date codes.
  40.      *
  41.      * @access    public
  42.      * @param    string 
  43.      * @param    integer 
  44.      * @return    integer 
  45.      */
  46.     function mdate($datestr$time false)    {
  47.         if ($time == false{
  48.             $time time();
  49.         }
  50.         
  51.         $datestr str_replace('%\\'''preg_replace("/([a-z]+?){1}/i""\\\\\\1"$datestr));
  52.         return date($datestr$time);
  53.     }
  54. }
  55.  
  56. // ------------------------------------------------------------------------
  57.  
  58. if (function_exists('days_in_month')) {
  59.     /**
  60.      * Number of days in a month
  61.      *
  62.      * Takes a month/year as input and returns the number of days
  63.      * for the given month/year. Takes leap years into consideration.
  64.      *
  65.      * @access    public
  66.      * @param    integer a numeric month
  67.      * @param    integer    a numeric year
  68.      * @return    integer 
  69.      */
  70.     function days_in_month($month false$year false{
  71.         if ($month === false{
  72.             $month date('n');
  73.         }
  74.         
  75.         if ($month OR $month 12{
  76.             return false;
  77.         }
  78.         
  79.         if is_numeric($year|| strlen($year!= 4{
  80.             $year date('Y');
  81.         }
  82.         
  83.         if ($month == 2{
  84.             if ($year 400 == || ($year == AND $year 100 != 0)) {
  85.                 return 29;
  86.             }
  87.         }
  88.         
  89.         $days_in_month    array(312831303130313130313031);
  90.         return $days_in_month[$month 1];
  91.     }
  92. }
  93.     
  94. // ------------------------------------------------------------------------
  95.  
  96. if (function_exists('local_to_gmt')) {
  97.     /**
  98.      * Converts a local Unix timestamp to GMT
  99.      *
  100.      * @access    public
  101.      * @param    integer Unix timestamp
  102.      * @return    integer 
  103.      */
  104.     function local_to_gmt($time false{
  105.         if ($time == ''{
  106.             $time time();
  107.         }
  108.     
  109.         return mktimegmdate("H"$time)gmdate("i"$time)gmdate("s"$time)gmdate("m"$time)gmdate("d"$time)gmdate("Y"$time));
  110.     }
  111. }
  112.  
  113. // ------------------------------------------------------------------------
  114.  
  115. if (function_exists('gmt_to_local')) {
  116.     /**
  117.      * Converts GMT time to a localized value
  118.      *
  119.      * Takes a Unix timestamp (in GMT) as input, and returns
  120.      * at the local value based on the timezone and DST setting
  121.      * submitted
  122.      *
  123.      * @access    public
  124.      * @param    integer Unix timestamp
  125.      * @param    string    timezone
  126.      * @param    bool    whether DST is active
  127.      * @return    integer 
  128.      */    
  129.     function gmt_to_local($time false$timezone 'UTC'$dst FALSE{
  130.         if ($time == false{
  131.             $time local_to_gmt();
  132.         }
  133.         
  134.         $time += timezones($timezone3600;
  135.         
  136.         if ($dst == TRUE{
  137.             $time += 3600;
  138.         }
  139.         
  140.         return $time;
  141.     }
  142. }
  143.     
  144. // ------------------------------------------------------------------------
  145.  
  146. if (function_exists('mysql_to_unix')) {
  147.     /**
  148.      * Converts a MySQL Timestamp to Unix
  149.      *
  150.      * @access    public
  151.      * @param    integer Unix timestamp
  152.      * @return    integer 
  153.      */
  154.     function mysql_to_unix($time{
  155.         // We'll remove certain characters for backward compatibility
  156.         // since the formatting changed with MySQL 4.1
  157.         // YYYY-MM-DD HH:MM:SS
  158.     
  159.         $time str_replace('-'''$time);
  160.         $time str_replace(':'''$time);
  161.         $time str_replace(' '''$time);
  162.     
  163.         // YYYYMMDDHHMMSS
  164.         return  mktime(
  165.                         substr($time82),
  166.                         substr($time102),
  167.                         substr($time122),
  168.                         substr($time42),
  169.                         substr($time62),
  170.                         substr($time04)
  171.                         );
  172.     }
  173. }
  174.     
  175. // ------------------------------------------------------------------------
  176.  
  177. if (function_exists('unix_to_mysql')) {
  178.     /**
  179.      * Unix to "MySql"
  180.      *
  181.      * Convierte una fecha en formato Unix a MySql
  182.      *
  183.      * @access    public
  184.      * @param    integer Unix timestamp
  185.      * @param    bool    whether to show seconds
  186.      * @return    string 
  187.     */
  188.     function unix_to_mysql($time FALSE$seconds TRUE{
  189.         if ($time === false{
  190.             $time time();
  191.         }
  192.         
  193.         if ($seconds{
  194.             return date('Y-m-d H:i:s'$time);
  195.         }
  196.         else {
  197.             return date('Y-m-d'$time);
  198.         }
  199.     }
  200. }
  201.     
  202. // ------------------------------------------------------------------------
  203.  
  204. if (function_exists('timezones')) {
  205.     /**
  206.      * Timezones
  207.      *
  208.      * Returns an array of timezones.  This is a helper function
  209.      * for various other ones in this library
  210.      *
  211.      * @access    public
  212.      * @param    string    timezone
  213.      * @return    string 
  214.      */
  215.     function timezones($tz false{
  216.         // Note: Don't change the order of these even though
  217.         // some items appear to be in the wrong order
  218.         
  219.         $zones array(
  220.                         'UM12' => -12,
  221.                         'UM11' => -11,
  222.                         'UM10' => -10,
  223.                         'UM9'  => -9,
  224.                         'UM8'  => -8,
  225.                         'UM7'  => -7,
  226.                         'UM6'  => -6,
  227.                         'UM5'  => -5,
  228.                         'UM4'  => -4,
  229.                         'UM25' => -2.5,
  230.                         'UM3'  => -3,
  231.                         'UM2'  => -2,
  232.                         'UM1'  => -1,
  233.                         'UTC'  => 0,
  234.                         'UP1'  => +1,
  235.                         'UP2'  => +2,
  236.                         'UP3'  => +3,
  237.                         'UP25' => +2.5,
  238.                         'UP4'  => +4,
  239.                         'UP35' => +3.5,
  240.                         'UP5'  => +5,
  241.                         'UP45' => +4.5,
  242.                         'UP6'  => +6,
  243.                         'UP7'  => +7,
  244.                         'UP8'  => +8,
  245.                         'UP9'  => +9,
  246.                         'UP85' => +8.5,
  247.                         'UP10' => +10,
  248.                         'UP11' => +11,
  249.                         'UP12' => +12
  250.                     );
  251.                 
  252.         if ($tz == false{
  253.             return $zones;
  254.         }
  255.     
  256.         if ($tz == 'GMT'{
  257.             $tz 'UTC';
  258.         }
  259.         
  260.         return isset($zones[$tz])) false $zones[$tz];
  261.     }
  262. }
  263.  
  264. if (function_exists('spanish_date')) {
  265.     /**
  266.      * Deuvelve la fecha en formato <i>$cFormat</i>.
  267.      * %A = Lunes, Martes, etc
  268.      * %e = dia del mes 1~31
  269.      * %B = Enero, Febrero, etc
  270.      * %Y = Año
  271.      *
  272.      * @param int $FechaStamp 
  273.      * @return string 
  274.      */
  275.     function spanish_date($cFormat='%A, %e de %B de %Y'$nTimestamp=null$cLocale APP_LOCALE{
  276.         
  277.         // Establece informacion de localidad.
  278.         setlocale(LC_TIME$cLocale);
  279.         
  280.         // Si no se paso la marca de tiempo pone una por defecto.
  281.         if ($nTimestamp === null{
  282.             $nTimestamp time();
  283.         }
  284.         
  285.         // Mapeo para argumentos NO-WINDOWS
  286.         $aMapping array(
  287.             '%C' => sprintf("%02d"date("Y"$nTimestamp100),
  288.             '%D' => '%m/%d/%y',
  289.             '%e' => sprintf("%' 2d"date("j"$nTimestamp)),
  290.             '%h' => '%b',
  291.             '%n' => "\n",
  292.             '%r' => date("h:i:s"$nTimestamp" %p",
  293.             '%R' => date("H:i"$nTimestamp),
  294.             '%t' => "\t",
  295.             '%T' => '%H:%M:%S',
  296.             '%u' => ($w date("w"$nTimestamp)) $w 7
  297.         );
  298.         $cFormat str_replace(array_keys($aMapping)array_values($aMapping)$cFormat);
  299.         
  300.         // Fecha de salida.
  301.         $cFecha strftime($cFormat$nTimestamp);
  302.         return $cFecha;
  303.     }
  304. }
  305.  
  306. if (function_exists('english_to_mysql')) {
  307.     /**
  308.      * Deuvelve la fecha para MySql.
  309.      * El parametro $cFecha recibe YYYY/DD/MM (formato ingles)
  310.      *
  311.      * @param string $cFecha 
  312.      * @return string 
  313.      */
  314.     function english_to_mysql($cFecha
  315.         $aFecha explode('/'$cFecha);
  316.         
  317.         return "{$aFecha[0]}-{$aFecha[2]}-{$aFecha[1]}";
  318.     }
  319. }
  320.  
  321. if (function_exists('mysql_to_english')) {
  322.     /**
  323.      * Deuvelve la fecha en formato ingles.
  324.      * El parametro $cFecha recibe YYYY-MM-DD (mysql)
  325.      *
  326.      * @param string $cFecha 
  327.      * @return string 
  328.      */
  329.     function mysql_to_english($cFecha
  330.         $aFecha explode('-'$cFecha);
  331.         
  332.         return "{$aFecha[0]}/{$aFecha[2]}/{$aFecha[1]}";
  333.     }
  334. }
  335.  
  336. if (function_exists('prepare_mysql_hour')) {
  337.     /**
  338.      * Formatea una hora para poder usarla en MySql.
  339.      * El parametro $cHora puede ser algo como esto:
  340.      * <i>4</i>, <i>15:50</i>
  341.      * 
  342.      * El parametro $nForce es para forzar la hora a cero
  343.      * en caso que $cHora corresponda a un horario incorrecto, EJ:
  344.      * <i>36:98:45</i>
  345.      *
  346.      * @param string $cHora 
  347.      * @param bool $nForce 
  348.      * @return string 
  349.      */
  350.     function prepare_mysql_hour($cHora$nForce=false
  351.         $aHora explode(':'$cHora);
  352.         
  353.         if (@$aHora[0|| @$aHora[023{
  354.             if ($nForce{
  355.                 $aHora[00;
  356.             }
  357.             else {
  358.                 return false;
  359.             }
  360.         }
  361.         if (@$aHora[1|| @$aHora[159{
  362.             if ($nForce{
  363.                 $aHora[10;
  364.             }
  365.             else {
  366.                 return false;
  367.             }
  368.         }
  369.         if (@$aHora[2|| @$aHora[259{
  370.             if ($nForce{
  371.                 $aHora[20;
  372.             }
  373.             else {
  374.                 return false;
  375.             }
  376.         }
  377.         
  378.         $cReturn sprintf('%02d'@$aHora[0]).
  379.             ':'.sprintf('%02d'@$aHora[1]).
  380.             ':'.sprintf('%02d'@$aHora[2]);
  381.             
  382.         return $cReturn;
  383.     }
  384. }
  385.  
  386. if (function_exists('mysql2date')) {
  387.     
  388.     /**
  389.      * Recibe una fecha o fecha/hora en formato de MySql (YYYY-MM-DD HH:MM:SS) y la
  390.      * pasa al formato especificado por $cFormat.
  391.      * 
  392.      * Para saber mas sobre el formato consultar la documentacion de la funcion strftime
  393.      * en el manual de PHP.
  394.      *
  395.      * @param string $cMySqlDate 
  396.      * @param string $cFormat 
  397.      * @return string 
  398.      * @see strftime
  399.      */
  400.     function mysql2date($cMySqlDate$cFormat='%d/%m/%Y'{
  401.         if ($cMySqlDate == ''{
  402.             return '';
  403.         }
  404.         
  405.         if (!preg_match("/([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})/"$cMySqlDate$aMySqlDate)) {
  406.             preg_match("/([0-9]{4})-([0-9]{2})-([0-9]{2})/"$cMySqlDate$aMySqlDate);
  407.         }
  408.         
  409.         $cReturn $cFormat;
  410.         $cReturn str_replace("%d"$aMySqlDate[3]$cReturn);
  411.         $cReturn str_replace("%m"$aMySqlDate[2]$cReturn);
  412.         $cReturn str_replace("%Y"$aMySqlDate[1]$cReturn);
  413.         if (isset($aMySqlDate[4])) {
  414.             $cReturn str_replace("%H"$aMySqlDate[4]$cReturn);
  415.             $cReturn str_replace("%i"@$aMySqlDate[5]$cReturn);
  416.             $cReturn str_replace("%s"@$aMySqlDate[6]$cReturn);
  417.         }
  418.         
  419.         return $cReturn;
  420.         
  421.         $nMarca strtotime($cMySqlDate);
  422.         
  423.         $cDateStr str_replace('%\\'''preg_replace("/([a-z]+?){1}/i""\\\\\\1"$cFormat));
  424.         return date($cDateStr$nMarca);
  425.     }
  426. }
  427.  
  428. if (function_exists('date2mysql')) {
  429.     
  430.     /**
  431.      * Recibe una fecha o fecha/hora en formato de MySql (YYYY-MM-DD HH:MM:SS) y la
  432.      * pasa al formato especificado por $cFormat.
  433.      * 
  434.      * Para saber mas sobre el formato consultar la documentacion de la funcion strftime
  435.      * en el manual de PHP.
  436.      *
  437.      * @param string $cMySqlDate 
  438.      * @param string $cFormat 
  439.      * @return string 
  440.      * @see strftime
  441.      */
  442.     function date2mysql($cDate$cFormat='%d/%m/%Y'$nTime=true{
  443.         if ($cDate == '' || $cDate == '__/__/____'{
  444.             return null;
  445.         }
  446.         
  447.         // Se definen los reemplazos por formato (el formato es igual al que usa strftime).
  448.         $aReemplazos['%d'array('f' => '([0-9]{1,2})''id' => 2);
  449.         $aReemplazos['%m'array('f' => '([0-9]{1,2})''id' => 1);
  450.         $aReemplazos['%y'array('f' => '([0-9]{2})''id' => 0);
  451.         $aReemplazos['%Y'array('f' => '([0-9]{2,4})''id' => 0);
  452.         $aReemplazos['%H'array('f' => '([0-9]{2})''id' => 3);
  453.         $aReemplazos['%i'array('f' => '([0-9]{2})''id' => 4);
  454.         $aReemplazos['%s'array('f' => '([0-9]{2})''id' => 5);
  455.         
  456.         $aReemplazosVacios['%d''[0-9]{1,2}';
  457.         $aReemplazosVacios['%m''[0-9]{1,2}';
  458.         $aReemplazosVacios['%y''[0-9]{2}';
  459.         $aReemplazosVacios['%Y''[0-9]{2,4}';
  460.         $aReemplazosVacios['%H''[0-9]{2}';
  461.         $aReemplazosVacios['%i''[0-9]{2}';
  462.         $aReemplazosVacios['%s''[0-9]{2}';
  463.         
  464.         $aMySqlDate array('0000''00''00''00''00''00')// Define los datos de fecha para MySql.
  465.         
  466.         // Cicla por todos los formatos de reemplazo.
  467.         foreach ($aReemplazos as $cClave => $aValores{
  468.             // Prepara la expresion regular.
  469.             $cFormatoTmp str_replace($cClave$aValores['f']$cFormat);
  470.             $cFormatoTmp strtr($cFormatoTmp$aReemplazosVacios);
  471.             $cFormatoTmp str_replace('/''\/'$cFormatoTmp);
  472.             
  473.             // Realiza la busqueda del dato de fecha, si la encuentra la pone en el array que contiene
  474.             // los datos de fecha para mysql.
  475.             if (preg_match("/{$cFormatoTmp}/"$cDate$aFechaTmp)) {
  476.                 if (count($aFechaTmp== 2{
  477.                     $aMySqlDate[$aValores['id']] $aFechaTmp[1];
  478.                 }
  479.             }
  480.         }
  481.         
  482.         if (strlen($aMySqlDate[0]== 2{
  483.             $aMySqlDate[0"20".$aMySqlDate[0];
  484.         }
  485.         
  486.         // Genera la fecha para MySql en el formato adecuado.
  487.         if ($nTime{
  488.             $cReturn "{$aMySqlDate[0]}-{$aMySqlDate[1]}-{$aMySqlDate[2]} {$aMySqlDate[3]}:{$aMySqlDate[4]}:{$aMySqlDate[5]}";
  489.         }
  490.         else {
  491.             $cReturn "{$aMySqlDate[0]}-{$aMySqlDate[1]}-{$aMySqlDate[2]}";
  492.         }
  493.         
  494.         
  495.         
  496.         if ($cReturn == '0000-00-00 00:00:00' || $cReturn == '0000-00-00'{
  497.             return null;
  498.         }
  499.         else {
  500.             return $cReturn;
  501.         }
  502.     }
  503. }
  504.  
  505. if (function_exists('date_diff')) {
  506.     
  507.     /**
  508.      * Devuelve la diferencia entre dos fechas.
  509.      *
  510.      * @param string $cFecha1 
  511.      * @param string $cFecha2 
  512.      * @return string 
  513.      */
  514.     function date_diff($cFecha1$cFecha2{
  515.         $nFecha1 strtotime($cFecha1);
  516.         $nFecha2 strtotime($cFecha2);
  517.         $nDiff = (int) (($nFecha1 $nFecha286400);
  518.         return $nDiff;
  519.     }
  520. }
  521.  
  522. if (function_exists('dec2hhmm')) {
  523.     
  524.     /**
  525.      * Convierte una cantidad decimal a horas y minutos: 3.25 -> 03:15, 2.50 -> 02:30.
  526.      *
  527.      * @param string $nDecimal 
  528.      * @return string 
  529.      */
  530.     function dec2hhmm($nDecimal{
  531.         $aTemp explode('.'sprintf('%02.2f'$nDecimal));
  532.         $cHora sprintf('%02s'$aTemp[0]).':'.sprintf('%02s',floor($aTemp[1.60));
  533.         return $cHora;
  534.     }
  535. }
  536.  
  537. if (function_exists('sec2time')) {
  538.     
  539.     /**
  540.      * Convierte una cantidad de segundos a formato HH:ii
  541.      *
  542.      * @param string $nSegundos 
  543.      * @return string 
  544.      */
  545.     function sec2time($nSegundos{
  546.         return dec2hhmm($nSegundos 3600);
  547.     }
  548. }
  549. ?>

Documentation generated on Tue, 22 Nov 2011 13:28:53 -0200 by phpDocumentor 1.4.3