Alireza Noori
Alireza Noori

Reputation: 15253

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?

Upvotes: 2

Views: 560

Answers (6)

Catalin
Catalin

Reputation: 868

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?

Upvotes: 0

salathe
salathe

Reputation: 51950

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

Upvotes: 8

KingCrunch
KingCrunch

Reputation: 131871

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

Upvotes: 4

onteria_
onteria_

Reputation: 70487

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

Upvotes: 4

Quamis
Quamis

Reputation: 11077

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

Upvotes: 3

deceze
deceze

Reputation: 522042

A possibility:

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

Upvotes: 2

Related Questions