1

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

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

DATE_FORMAT(datefield, '%d/%m/%Y | %H:%i:%s') to be exact.
2
date('d/m/Y | G:i:s', strtotime($theOriginalTime))

That should do what you need.

4 Comments

Wasteful - easier to do the conversion in MySQL and save the overhead of the strtotime() parsing.
Oh the age old debate begins again. I'm not a fan of putting business logic in a database. It's a personal preference.
True enough. Depends on how efficient the OP needs things to be. Pulling out a kajillion dates would suggest doing the date formatting in the database. Doing it once an hour makes the PHP overhead a bit easier to digest.
Now if we could only teach politicians to have polite conversations like this.
1

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

2 Comments

Wasteful - easier to do the conversion in MySQL and save the php-side roundtrip through strtotime or the unix_timestamp conversion
I'd say both are valid approaches, depending on your design pattern. If for instance the database interaction code and the formatting code are separate, doing the formatting in PHP is perfectly valid.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.