Tuesday, February 16, 2010

Date Convertion in PHP... Easy Move..

In this code we are capable to give Source date format and Destination date format as parameters our function of date conversion.

As in this example:
Source Format: 'd/m/Y';
Destination Format: 'Y-m-d';
Input Date: "25/12/2005";
Output Date: "2005-12-25".


[?php //Php start tag...
/**
* Converts a date string from one format to another (e.g. d/m/Y => Y-m-d, d.m.Y => Y/d/m, ...)
*
* @param string $date_format1
* @param string $date_format2
* @param string $date_str
* @return string
*/
function dates_interconv( $date_format1, $date_format2, $date_str )
{
$base_struc = split('[/.-]', $date_format1);
$date_str_parts = split('[/.-]', $date_str );

$date_elements = array();

$p_keys = array_keys( $base_struc );
foreach ( $p_keys as $p_key )
{
if ( !empty( $date_str_parts[$p_key] ))
{
$date_elements[$base_struc[$p_key]] = $date_str_parts[$p_key];
}
else
return false;
}

$dummy_ts = mktime( 0,0,0, $date_elements['m'],$date_elements['d'],$date_elements['Y']);

return date( $date_format2, $dummy_ts );
}

$df_src = 'd/m/Y';
$df_des = 'Y-m-d';

$iso_date = dates_interconv( $df_src, $df_des, '25/12/2005');
?>


output:

2005-12-25

No comments:

Post a Comment