开发者

Parse and reformat a datetime string

I have a string sent from database, I want to turn it into a date/time string. The source string is:

20110524153631

I want it to be:

2011-05-24 15:36:31

I know I can use multiple inserts but I want to know whether there's a more easy way to do this.开发者_运维问答 How can I achive this?


In PHP 5.3 you can use the DateTime::createFromFormat() method (or its date_create_from_format() alias).

echo DateTime::createFromFormat(
    'YmdHis',
    '20110524153631'
)->format('Y-m-d H:i:s');

For earlier versions (why?) you could play around with the string in any number of boring, or fanciful, ways.

vprintf("%s-%s-%s %s:%s:%s", sscanf("20110524153631", "%4s%2s%2s%2s%2s%2s"));


Instead of doing that, we can use DateTime functionality to parse the date for us:

$date = DateTime::createFromFormat('YmdHis', '20110524153631');
echo "This date is: " . $date->format('Y-m-d H:i:s') . "\n";

$ php test.php
This date is: 2011-05-24 15:36:31


$in = '20110524153631';
list(
    $year,
    $month,
    $day,
    $hour,
    $minute,
    $second) = sscanf($in, '%4d%2d%2d%2d%2d%2d');
echo sprintf('%4d-%02d-%02d %02d:%02d:%02d',
    $year,
    $month,
    $day,
    $hour,
    $minute,
    $second);


$str = '20110524153631';
echo preg_replace("/(.{4})(.{2})(.{2})(.{2})(.{2})(.{2})/", "\$1-\$2-\$3 \$4:\$5:\$6", $str);


A possibility:

echo preg_replace('/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/',
         '$1-$2-$3 $4:$5:$6', '20110524153631');


Why not use http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_str-to-date in the SELECT or INSERT query?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜