PHP date_parse_from_format( ) alternative in PHP 5.2

Acacio picture Acacio · Jul 12, 2011 · Viewed 10.7k times · Source

Since date_parse_from_format( ) is available only in PHP 5.3, I need to write a function that mimics its behaviour in PHP 5.2.

Is it possible to write this function for PHP 5.2 and make it work exactly the same way that it does in PHP 5.3?

Example:

For this input:

<?php
$date = "6.1.2009 13:00+01:00";
print_r(date_parse_from_format("j.n.Y H:iP", $date));
?>

I need this output:

Array
(
    [year] => 2009
    [month] => 1
    [day] => 6
    [hour] => 13
    [minute] => 0
    [second] => 0
    [fraction] => 
    [warning_count] => 0
    [warnings] => Array
        (
        )

    [error_count] => 0
    [errors] => Array
        (
        )

    [is_localtime] => 1
    [zone_type] => 1
    [zone] => -60
    [is_dst] => 
)

Answer

Ujjwal Manandhar picture Ujjwal Manandhar · Jul 12, 2011
<?php
function date_parse_from_format($format, $date) {
  $dMask = array(
    'H'=>'hour',
    'i'=>'minute',
    's'=>'second',
    'y'=>'year',
    'm'=>'month',
    'd'=>'day'
  );
  $format = preg_split('//', $format, -1, PREG_SPLIT_NO_EMPTY); 
  $date = preg_split('//', $date, -1, PREG_SPLIT_NO_EMPTY); 
  foreach ($date as $k => $v) {
    if ($dMask[$format[$k]]) $dt[$dMask[$format[$k]]] .= $v;
  }
  return $dt;
}
?>

Example 1:

<?php
    print_r(date_parse_from_format('mmddyyyy','03232011');
?>

Output 1:

Array ( [month] => 03 [day] => 23 [year] => 2011 )

Example 2:

 <?php
    print_r(date_parse_from_format('yyyy.mm.dd HH:ii:ss','2011.03.23 12:03:00'));
 ?>

Output 2:

Array ( [year] => 2011 [month] => 03 [day] => 23 [hour] => 12 [minute] => 03 [second] => 00 )