Aaron
Aaron

Reputation: 11673

How to format a date using preg_split

2011-03-30 17:47:31 So this is the date in my mysql database;

what do I do to do that?

I want it to look like 30/03/2011 | 17:47:31

Upvotes: 1

Views: 1617

Answers (4)

ridgerunner
ridgerunner

Reputation: 34395

This is easily solved with a regex. Here is a tested PHP function which reformats any and all such dates in a given text string:

function convert_dates($text) {
    // Convert 2011-03-30 17:47:31 to 30/03/2011 | 17:47:31
    $re = '/# Match components of a YYYY-MM-DD HH:MM:SS date.
        \b                     # Begin on word boundary
        (\d{4})-               # $1: Year.
        (\d{2})-               # $2: Month.
        (\d{2})[ ]             # $3: Day.
        (\d{2}):               # $4: Hour.
        (\d{2}):               # $5: Minute.
        (\d{2})                # $6: Second.
        \b                     # End on word boundary.
        /Sx';
    $replace = '$3/$2/$1 | $4:$5:$6';
    return preg_replace($re, $replace, $text);
}

Upvotes: 0

k to the z
k to the z

Reputation: 3185

date('d/m/Y | G:i:s', strtotime($theOriginalTime))

That should do what you need.

Upvotes: 2

Gustav Larsson
Gustav Larsson

Reputation: 8487

I'm not sure why you want to use preg_split, just do:

date("d/m/Y | G:i:s", strtotime($timestamp));

Or fetch the unix timestamp from MySQL with UNIX_TIMESTAMP() and then do:

date("d/m/Y | G:i:s", $unix_timestamp);

Upvotes: 1

John Bartholomew
John Bartholomew

Reputation: 6596

Extract the date with the format you want, by using the DATE_FORMAT function in your SQL query.

Upvotes: 2

Related Questions