CodeIgniter Forums

Full Version: Convert a date, which is stored in a mysql database [SOLVED]
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]testietest[/eluser]
Hi fellow Coders,

I'm new to the whole CodeIgniter thing (to be honest I'm fairly new to programming at all). But my question is, I have this mysql database, with some random text fields and a date field. When I echo the date in a webpage with the following code:
Code:
<?php echo $r->date;?>
it'll use the year/month/day format, where I want it to show the day/month year format. I've been looking around at the forums (both the CodeIgniter and PHP forum) but I can't really find a way to convert it to the way I want it to show up.

So could anyone help me out here?

With kind regards and thank you for your time,

Wesley

El Forum

[eluser]sl3dg3hamm3r[/eluser]
DateTime::format is your friend...

sl3dg3

El Forum

[eluser]n0xie[/eluser]
You should convert the MySQL date format to an UNIX timestamp (use the datehelper for this) so you can format it using the date() function.

Take a look at my reply here.

El Forum

[eluser]Flemming[/eluser]
or if you just want to convert it to dd-mm-yyyy you can run it through something like this:

Code:
function english_date($date)
{
    return substr($date,8,2).'-'.substr($date,5,2).'-'.substr($date,0,4);
}

El Forum

[eluser]testietest[/eluser]
Hey guys,

Thank you for all the information. I'll dig into the date-time format or the solution Flemming came up with

With kind regards,

Wesley

El Forum

[eluser]Phil Sturgeon[/eluser]
No digging required.

Code:
$datetime = new DateTime($r->date);
echo $datetime->format('jS, F Y');

If you are feeling REALLY lazy...

Code:
<?php echo date('jS, F Y', strtotime($r->date));?>

I would go with DateTime though, much more useful.

El Forum

[eluser]testietest[/eluser]
[quote author="Phil Sturgeon" date="1257958564"]No digging required.

Code:
$datetime = new DateTime($r->date);
echo $datetime->format('jS, F Y');

If you are feeling REALLY lazy...

Code:
<?php echo date('jS, F Y', strtotime($r->date));?>

I would go with DateTime though, much more useful.[/quote]

Hi Phil,

Extremely kind of you to give me these solutions. Exactly what I was looking for. Thank you a lot! Final code became
Code:
<?php echo date('d-m-Y', strtotime($r->date));?>
because I like all numbers better.

With kind regards,

Wesley

El Forum

[eluser]Jondolar[/eluser]
An alternative would be to pull it out of the database in the format that you want to use to display it in. Since MySQL (et. al.) has to convert the field anyway (dates are stored as a timestamp), you might as well just have the database convert it once and be done with it.

select DATE_FORMAT(datefield, '%W %M %Y') as TheDate from mytable;

<?php echo $r->TheDate);?>

Good luck with your project.