What is the simplest, fastest way to complete the PHP code below such that the output is in a user-friendly format (for example, "October 27, 2006")?
$result = mysql_query("SELECT my_timestamp FROM some_table WHERE id=42", $DB_CONN);
$row = mysql_fetch_array($result);
$formatted_date = ???($row['my_timestamp']);
echo $formatted_date;
You could use MySQL to do this for you,
$result = mysql_query("SELECT DATE_FORMAT(my_timestamp, '%M %d, %Y) AS my_timestamp FROM some_table WHERE id=42", $DB_CONN);
$row = mysql_fetch_array($result);
$formatted_date = $row['my_timestamp'];
echo $formatted_date;
Or use PHP,
$result = mysql_query("SELECT my_timestamp FROM some_table WHERE id=42", $DB_CONN);
$row = mysql_fetch_array($result);
$formatted_date = strftime('%B %d, %y', $row['my_timestamp']);
echo $formatted_date;
You want the date() function.
If you've got a DATE or DATETIME column, you can use SELECT UNIX_TIMESTAMP(mycolumn) AS mycolumn to convert it to a unix timestamp for the date function to use.
You should definitely use the DateTime class (or any home grew equivalent class), over de Date function, and not use timestamps:
At the end of the day, don't rely on timestamps, unless you are in an english only environment, and deal with dates between 1970 and 2032 only...!
If you have your tables indexed on that date field and you use a mysql data format function in your call.. (ie .. SELECT DATE_FORMAT(my_timestamp, '%M %d, %Y) AS my_time ) it will destroy your indexing. Something to keep in mind. We have seen dramatic increases in speed in removing all functioning from our sql statements and letting php handle it all. Functioning such as formatting dates and simple math
I use:
date("F j, Y", strtotime($row['my_timestamp']))
or you can change the SELECT to: DATE_FORMAT(field,'%d %M, %Y') as datetime
You have a choice. You can use the date() function in PHP and process the output from MySQL, or you can use the date_format() function in MySQL and have it return a formatted string to begin with.
In my experience is that it doesn't really matter which you use, but BE CONSISTENT. They have different formatting parameters, so if you use both in a given application you'll spend a lot of time trying to remember if 'W' gives you the name of the day of the week or the week of the year.
Have the database do the formatting for you. It is far less susceptible to error because you are not reading a string and converting it. Instead, the database is going from its native format to a string.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.