PDA

View Full Version : php date convert function


mic2100
05-18-2006, 10:22 AM
I have been using mySQL dates and the fromat they seem to always output is YYYY-MM-DD (HH:MM:SS), i was having to change each date to display on the screen for the users and this was becoming a problem. So i have written this function for converting dates into the correct formats.


function datechangefromDB($value, $type);
{

//type 1 is for just a date
if($type == 1)
{

//this breaks up the date into seperate parts
array($date = explode("-", $value));

//this sets the date in to the correct format
// 0 = YEAR, 1 = MONTH, 2 = DAY
$outputdate = $date[2]."-".$date[1]."-".$date[0];

echo $outputdate;

}
//type 2 is for datetime
elseif($type == 2)
{

//this explodes the datetime into seperate parts
array($datetime = explode(" ", $value));
//this explodes the date into seperate parts
array($date = explode("-", $datetime[0]));

//sets the outputdate to the correct format
// date = (0 = YEAR, 1 = MONTH, 2 = DAY)
// datetime = (0 = date, 1 = TIME)
$outputdate = $date[2]."-".$date[1]."-".$date[0]." ".$datetime[1];

echo $outputdate;

}

}


This has made my life easier, i'm sure there is a better way of doing it but this will do 4 me.

TopFighter
05-18-2006, 10:24 AM
thanks for sharing

dsk3801
05-20-2006, 06:06 AM
You could also use MySQL's date_format function to have a date, time, or datetime field converted just about anyway you'd like:

http://dev.mysql.com/doc/refman/4.1/en/date-and-time-functions.html

(Do a CTRL+F and look for date_format and it will take you right to that section).

mic2100
05-20-2006, 08:12 AM
nice 1 i knew there was an easier way. Cheers!!!!

mic2100
05-20-2006, 08:15 AM
cool i like that, i bin messin about for ages till i come up with that function, but u made it even easier :thumbsup:

trib4lmaniac
05-20-2006, 02:13 PM
strtotime (http://php.net/strtotime) and date (http://php.net/date).