String to date conversion in PHP
Question
I'd like to convert such a date '2012 30 March 9:30 pm' into this format 2012-03-30 09:30:00 What is the easiest way to do that? I need it to be working on PHP 5.2 and older, so this solution isn't of any use for me
date_format('Y-m-d H:M:S',date_create_from_format('Y m F g:i A', '2012 30 March 9:30 pm'))
Solution
This will extract each component from the date and rearrange it so that strtotime()
understands. Convert to any date format you want after that.
Using regex is probably overkill though.
function parse_date_time_to_ts($dt)
{
$dt_pattern = '#([0-9]{4})\s+([0-9]{1,2})\s+([a-z]+)\s+([0-9]{1,2}:[0-9]{2})\s+(am|pm)#is';
$dt_replace = '$2 $3 $1 $4 $5';
return strtotime(preg_replace($dt_pattern, $dt_replace, $dt));
}
OTHER TIPS
Use sscanf(), then make the string in the correct format, strtotime() on it and then date() with the format required.
EDIT: following Stewie advice:
<?php
list($year, $day, $month, $hour, $minute, $ampm) = sscanf("2012 30 March 9:30 pm
", "%d %d %s %d:%d %s");
if($ampm == 'pm') $hour += 12;
echo date("Y-m-d H:i:s", strtotime($day . ' ' . $month . ' ' . $year . ' ' . $ho
ur . ':' . $minute));
http://php.net/manual/en/function.strtotime.php#106043
see the link of official documentation and an user contribution...
Try this
list($year, $month, $day, $year, $hour, $minutes, $a) = sscanf("2012 30 March 9:30 pm", "%d %d %d $s $d:$d $s");
echo date("Y-m-d h:i:s", strtotime($day." ".$month." ".$year." ".$hour.":".minutes." ".$a));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow