tags:

views:

56

answers:

4

Hi all,

I think this is a simple question. We have a MySQL database with a DATE field, the date is stored in US format (2010-06-01).

In my PHP page where I'll display the date, I simply want to convert this date into a UK format (01-06-2010).

Any help and advice appreciated!

Thanks,

Homer.

+5  A: 

You didn't specify and your example is ambiguous, but I'll assume you're talking about outputting in day-month-year format. You can use strtotime to parse a string date into a unix timestamp, and then give that timestamp to date along with the format that you'd like to output your date in:

date("d-m-Y", strtotime($date_from_mysql));

The manual page for date lists all the formatting options that you can give. In this case, d represents the day as a zero-padded number, m represents the month as a zero-padded number, and Y represents the year as a four digit number. Any characters that don't have a specific meaning for date come across as-is.

Daniel Vandersluis
+1. It's probably m-d-Y, though, judging from the OP's sample MySQL date.
gclaghorn
@gclaghorn MySQL `DATE` format is 'YYYY-MM-DD' (http://dev.mysql.com/doc/refman/5.6/en/datetime.html). So if 2010-06-01 is a MySQL `DATE`, it means June 1 2010 (and thus 01-06-2010 is DD-MM-YYYY).
Daniel Vandersluis
Perfect - thanks Daniel - apologies if the question was a little ambiguous.
Homer_J
+1  A: 

You can parse the date with this function:

http://php.net/manual/en/function.strtotime.php

It will return an integer which is number of seconds since 1970 (called a Unix timestamp).

Then use this function to format that number any way you like:

http://ca3.php.net/manual/en/function.date.php

Helgi Hrafn Gunnarsson
+3  A: 

You can do it right from mysql using DATE_FORMAT() function. example : "SELECT DATE_FORMAT(date_column,'%d-%m-%Y') as my_formated_date;" will do what you need , just make sure to use in fetch method my_formated_date column

Centurion
+1  A: 

You can also create a Date object in PHP using the DateTime::createFromFormat feature.

<?php
    $date = DateTime::createFromFormat('Y-m-d', $sql_date);
    echo $date->format('d-m-Y');
?>
Codeacula
Quick edit. Thought I had a stray apostrophe, turns out I was missing the other.
Codeacula
Not quite what I was looking for but helpful - thanks!
Homer_J