PDA

View Full Version : PHP Date



kaos
09-12-2011, 06:29 AM
hey guys

im kinda new to php and need some help with date format conversions. specifically when selected from a SQL database. Basically, i have a date column in my datatable and i call it in with

$row['Date']
it will then show up like it is in the table as 2011-09-24. is there any way to convert this to something like September 9, 2011???????

mburt
09-12-2011, 10:13 AM
<?php
function convert_time($x) {
$spl = explode("-", $x);
$y = $spl[0]; $m = $spl[1]; $d = $spl[2];
$months = array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
return $months[$m-1]." ".$d.", ".$y;
}
//example usage
echo convert_time("2011-04-20");
//or more specifically, convert_time($row['Date']);
?>

Note: this is untested, however it should work.

fastsol1
09-12-2011, 11:51 AM
Here's a far simpler way.

date("F j, Y", strtotime($row['Date']))

traq
09-12-2011, 03:25 PM
Here's a far simpler way.

date("F j, Y", strtotime($row['Date']))

absolutely. to expand on that, I highly recommend NOT using mysql's version of 'DATETIME' or 'TIMESTAMP'. It saves human-readable date strings, but that makes it difficult to do anything with them (compare dates, change formats, etc.).

a better solution is to save a unix timestamp (e.g., using time() ) which you can operate on or convert into a readable string using date() as fastsol does above.

kaos
09-13-2011, 11:43 PM
Thanks everybody!!!

JShor
09-14-2011, 01:42 AM
absolutely. to expand on that, I highly recommend NOT using mysql's version of 'DATETIME' or 'TIMESTAMP'. It saves human-readable date strings, but that makes it difficult to do anything with them (compare dates, change formats, etc.).

a better solution is to save a unix timestamp (e.g., using time() ) which you can operate on or convert into a readable string using date() as fastsol does above.

I second this. ALWAYS use time() for storing time. It's easy to sort, compare, store and convert. And it stores time down to the second.