Search code examples
phpdatestrtotimestrptime

String to date conversion in PHP


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));
    }