Homer_J
Homer_J

Reputation: 3323

PHP convert date from a MySQL query

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.

Upvotes: 3

Views: 8776

Answers (4)

Codeacula
Codeacula

Reputation: 2368

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

Upvotes: 1

Centurion
Centurion

Reputation: 5281

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

Upvotes: 3

Teekin
Teekin

Reputation: 13259

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

Upvotes: 1

Daniel Vandersluis
Daniel Vandersluis

Reputation: 94123

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.

Upvotes: 14

Related Questions