Page 1 of 1

Formatting the date

Posted: Sat Jan 25, 2003 12:43 pm
by evilmonkey
I have a date in a database, and it loks like this: 030115 (january 15, 2003). I wanted it make it look half-decent by dong this:

Code: Select all

$date_from_db = "$row->date";
$formatted_date = date("m/j/y", time($date_from_db));
echo $formatted_date;
The problem is it gives me today's date. Where is my problem?

Thanks.

Posted: Sat Jan 25, 2003 2:33 pm
by mydimension
the php date and time functions are designed to work with unix timestamps. the date you have in your db is not a unixtimestamp and is therefore an invalid value, causing these functions to default to the current date and time. try this:

Code: Select all

$date_array = explode(":", chunk_split($date_from_db, 2, ":");
$formatted_date = date("m/j/y", mktime(0, 0, 0, $date_array[1], $date_array[2], $date_arry[0]);
note: not tested

Posted: Sat Jan 25, 2003 2:44 pm
by twigletmac
The reason why you are getting the current date is because time() doesn't accept any arguments and only ever returns the current UNIX timestamp - to get the timestamp for another time you need to use mktime() as mydimension does in his example.

It would be easier if you stored the date in the database (assuming MySQL here 'cause you don't say which you use) as a DATE or TIMESTAMP field, that way you can use the database to format the date when you extract it:
http://www.mysql.com/doc/en/Date_and_ti ... ml#IDX1281

Mac

Posted: Sat Jan 25, 2003 2:51 pm
by evilmonkey
Mac, this method will most likely not work for me because I'm using phpmyadmin (NULL field) to do this work. Yes, I use mysql.

My Demension, your code returns a parse error that I cannot fix..
Someone, please give me the correct version of MD's code.

Thanks.

Posted: Sat Jan 25, 2003 2:56 pm
by twigletmac
I'm not sure why using a DATE or TIMESTAMP field would not work because of using phpMyAdmin - it really is the best way to store dates as it makes them a lot easier to work with and to extract the way you want.

However, the parse error with MyDimension's code - there's a parenthesis missing on this line:

Code: Select all

$date_array = explode(":", chunk_split($date_from_db, 2, ":"));
Mac

Posted: Sat Jan 25, 2003 3:09 pm
by mydimension
thx mac :oops:

Posted: Sat Jan 25, 2003 3:14 pm
by evilmonkey
it gives me the date as 2000 for some reason...but at least I got it working.

Any ideas on how to fix the 200 problem?

Thanks