Page 1 of 1

Date conversion

Posted: Mon Feb 24, 2003 7:58 pm
by Kriek
Converting date format from MySQL (yyyy-mm-dd) field (type=date) into a word format using PHP.

Example: 2003-02-24 into February 24th 2003

The problem is when I echo $date It displays as December 31st 1969 instead of February 24th 2003

Code: Select all

<?php
    include "config.php";
    $db = mysql_connect($db_host, $db_user, $db_pass);
    mysql_select_db ($db_name) or die ("Cannot connect to database");
    $query = "SELECT title, news, author, date FROM news ORDER BY id DESC LIMIT 10";
    $result = mysql_query($query);
    while ($r = mysql_fetch_array($result)) {
        $title = $r["title"];
        $news = $r["news"];
        $author = $r["author"];
        $date = date("F jS  Y", $r["date"]);
    }
    mysql_close($db);
?>

Posted: Tue Feb 25, 2003 12:28 am
by hob_goblin

Code: Select all

<?php 

$date = "2003-02-24";
$date = strtotime($date);
echo date("F jS Y", $date);

?>
works for me!
http://www.php.net/strtotime

So try this:

Code: Select all

<?php 
    include "config.php"; 
    $db = mysql_connect($db_host, $db_user, $db_pass); 
    mysql_select_db ($db_name) or die ("Cannot connect to database"); 
    $query = "SELECT title, news, author, date FROM news ORDER BY id DESC LIMIT 10"; 
    $result = mysql_query($query); 
    while ($r = mysql_fetch_array($result)) &#123; 
        $title = $r&#1111;"title"]; 
        $news = $r&#1111;"news"]; 
        $author = $r&#1111;"author"]; 
        $date = strtotime($r&#1111;"date"]);
        $date = date("F jS  Y", $date); 
    &#125; 
    mysql_close($db); 
?>

Posted: Tue Feb 25, 2003 2:52 am
by twigletmac
Why not get MySQL to do the date formatting for you?
http://www.mysql.com/doc/en/Date_and_ti ... tions.html

Code: Select all

SELECT title, news, author, DATE_FORMAT(date, '%M %D %Y') AS date FROM news ORDER BY id DESC LIMIT 10
Mac

Posted: Tue Feb 25, 2003 4:19 am
by Always_Stuck
I have never been able to help anyone with code before, but will give this one a shot... this is the code I use

Code: Select all

<?php

// The following $Date_Posted is actually stored in mysql
$Date_Posted = "2002-01-17";

// Break up the date and store the year, month and date into an array
list($y,$m,$d) = explode('-', $Date_Posted); 

// Use mktime to convert the date into the format "17th January 2003"
$phptodaysdate = date("jS F Y", mktime(0, 0, 0, $m, $d, $y)); 
?>

The previous code will turn "2002-01-17" into "17th January 2003"


Hope that helps

Posted: Tue Feb 25, 2003 5:43 am
by twigletmac
Although with MySQL doing the work you do cut down on a few lines of code.

Mac

Posted: Tue Feb 25, 2003 12:09 pm
by Kriek
Thanks guys!

Dan, that was exactly what I was looking for =)