PHP: Format MySQL DATE and DATETIME

25.06.2008 Tags: tutorial,PHP,Version française disponible ici! A couple of days ago, I saw a website with some PHP scripts and functions, including one allowing you to convert MySQL dates (in YYYY-MM-DD format) to a "human" format, something like DD-MM-YYYY. Their method (well, "their" method... most of the snippets I saw afterwards worked with the same one) is to do an explode() of the date string, rebuild an array with the values inverted and implode array's values with a delimiter. It looks like this:

<?php

function dateConv($value) {

$table = explode('-',$value);
$temp_array = array();

for ($i=2;$i>=0;$i--) {

array_push($temp_array,$table[$i]);

}

$final = implode('/',$temp_array);

print_r($final);

}

?>


Hmm yeah, it does work but we can do better: using strtotime() and strftime().
strtotime() converts an english date format to a timestamp.
strftime() formats a date to the given format.
Ok, and what can we do with that?

<?php

function dateConv($value) {

$final = strftime('%d-%m-%Y', strtotime($value));

print_r($final);

}

?>


We convert $value (our date) to a timestamp and format it to what we want, here to something with this format: DD-MM-YYYY.
We also can go further and covnert a DATETIME format:

<?php

function dateConv($value) {

$final = strftime('%d-%m-%Y %T', strtotime($value)); // %T is the format HH:MM:SS

print_r($final);

}

?>


Let's imagine our DATETIME is 2008-08-25 22:47:04, this function will return 25-08-2008 22:47:04
We can also return only the date by removing the format tag ' %T' in our function.
And why not also defining our delimiter? Not everyone wants date's values separated by a - but prefers a /

<?php

function dateConv($value,$delimiter) {

$final = strftime('%d'.$delimiter.'%m'.$delimiter.'%Y %T', strtotime($value));

print_r($final);

}

?>


You can go to php.net to have the list of format tags.

Add a comment

*: Mandatory fields. You e-mail address will never be publicly displayed nor transmitted to someone.

Comments

gravatar_mysql format date
mysql format date 07.01.2010, 19:57:33 Here is a good website for formatting dates using the MySQL date_format function http://www.mysqlformatdate.com