0

I am using a datetime format in a table in my database.

It is formatted like this: yyyy/mm/dd 00:00:00

1) How do I extract just the date, just the time from the value? 2) How do I reformat the date to be like mm/dd/yyyy when I output it? 3) How do I reformat the time to be hh:mm am/pm when I output it?

Thanks

5 Answers 5

2

Try this:

date('Y-m-d', strtotime( $thetime ) );
date('H:i:s', strtotime( $thetime ) );
date('g:i a', strtotime( $thetime ) );

Catch up on reading about the date function.

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

Comments

1

You can accomplish this on the server side using MySQL's DATE_FORMAT function:

1) How do I extract just the date, just the time from the value?

SELECT DATE(dateColumn)

2) How do I reformat the date to be like mm/dd/yyyy when I output it?

SELECT DATE_FORMAT(dateColumn, '%m/%d/%Y')

3) How do I reformat the time to be hh:mm am/pm when I output it?

SELECT DATE_FORMAT(dateColumn, '%h:%i %p')

1 Comment

you can but OP wants to be able to manipulate one result rather that querying serveral times. the alternative is selecting all the required formats in the query.
0

You extract the format from the query:

SELECT DATE(`datetime_column`) as `date` FROM `table`

Will only retrieve the date part.

For date/time formatting in PHP, see the DateTime object.

Comments

0

1) MySQL ususally formats datetime as yyyy-mm-dd hh:mm:ss, in this case use the following code to format, where $sql is your database datetime string and use whatever information you need:

$year = $sql[0] . $sql[1] . $sql[2] . $sql[3];
$month = $sql[5] . $sql[6];
$day = $sql[8] . $sql[9];
$hour = $sql[11] . $sql[12];
$min = $sql[14] . $sql[15];
$sec = $sql[17] . $sql[18];

2) http://php.net/manual/de/function.date.php to format

3) http://php.net/manual/de/function.date.php to format ;-)

Comments

0

you could use the datetime obj...

$dateTime = new DateTime($dateTimeFromDB);

$date = $dateTime->format('Y/m/d');;
$time = $dateTime->format('H:i:s');

$formattedDate = $dateTime->format('m/d/Y');
$formattedTime = $dateTime->format('g:i a');

echo each of them and it should deliver what you are after...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.