3

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.

4 Answers 4

14

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.

Sign up to request clarification or add additional context in comments.

4 Comments

+1. It's probably m-d-Y, though, judging from the OP's sample MySQL date.
@gclaghorn MySQL DATE format is 'YYYY-MM-DD' (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).
Perfect - thanks Daniel - apologies if the question was a little ambiguous.
Simplest & best answer. I hate two lines of code such a simple task. Thanks bro
3

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

Comments

1

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:

https://www.php.net/manual/en/function.date.php

Comments

1

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');
?>

1 Comment

Quick edit. Thought I had a stray apostrophe, turns out I was missing the other.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.