String to date conversion in PHP

空扰寡人 提交于 2019-12-11 17:25:42

问题


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'))

回答1:


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



回答2:


Use sscanf(), then make the string in the correct format, strtotime() on it and then date() with the format required.




回答3:


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



回答4:


http://php.net/manual/en/function.strtotime.php#106043

see the link of official documentation and an user contribution...




回答5:


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


来源:https://stackoverflow.com/questions/9720356/string-to-date-conversion-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!