Converting a Date Into Another Format
It’s very useful to convert a PHP date into the datetime MySQL format (whose format is Y-m-d H:i:s).
/**
* Converts a date and time string from one format to another (e.g. d/m/Y => Y-m-d, d.m.Y => Y/d/m, ...)
*
* You can use only these "format character"s for the date:
* d F m M Y y H i s
*
* As separators between tokens you can use these characters:
* :
* /
* .
* [space]
* -
*
* Usage example:
* $df_src = 'd M Y';
* $df_des = 'Y-m-d H:i:s';
* echo dates_interconv( $df_src, $df_des, '20 May 2007');
*
* @param string $date_format1
* @param string $date_format2
* @param string $date_str
* @return string
*/
function dates_interconv($date_format1, $date_format2, $date_str)
{
// extracting the tokens
$base_struc = split('[:/. -]', $date_format1);
$date_str_parts = split('[:/. -]', $date_str ); /*
// creating $date_elements as such an array:
Array
(
[m] => 12
[d] => 10
[y] => 06
)
*/
$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;
}
// Doing some adjustment in order to have all the "format character"s needed to create a valid timestamp
if (array_key_exists('M', $date_elements)) {
$Mtom=array(
"Jan"=>"01",
"Feb"=>"02",
"Mar"=>"03",
"Apr"=>"04",
"May"=>"05",
"Jun"=>"06",
"Jul"=>"07",
"Aug"=>"08",
"Sep"=>"09",
"Oct"=>"10",
"Nov"=>"11",
"Dec"=>"12",
);
$date_elements['m']=$Mtom[$date_elements['M']];
}
if (array_key_exists('F', $date_elements)) {
$Ftom=array(
"January"=>"01",
"February"=>"02",
"March"=>"03",
"April"=>"04",
"May"=>"05",
"June"=>"06",
"July"=>"07",
"August"=>"08",
"September"=>"09",
"October"=>"10",
"November"=>"11",
"December"=>"12",
);
$date_elements['m']=$Ftom[$date_elements['F']];
}
if (array_key_exists('y', $date_elements)) {
$date_elements['Y'] = "20".$date_elements['y'];
}
// using @ because some bit of the array could not exist
$dummy_ts = @mktime(
$date_elements['H'],
$date_elements['i'],
$date_elements['s'],
$date_elements['m'],
$date_elements['d'],
$date_elements['Y']
);
return date( $date_format2, $dummy_ts );
}