问题
I'm trying to format a MySQL formatted date (YYYY-MM-DD) and wish to display the month and year, "September 2012" for example.
My code:
<?php echo htmlspecialchars($row["date"], ENT_QUOTES, "UTF-8"); ?>
Does anyone know how I can accomplish this?
回答1:
You can use DateTime to format your date how you'd like:
$date = DateTime::createFromFormat('Y-m-d', $row["date"]);
echo htmlspecialchars($date->format('F Y'), ENT_QUOTES, "UTF-8");
So with a date like this:
$row['date'] = '2012-09-25';
This will print:
September 2012
回答2:
Either select it in that format directly from SQL, e.g.
SELECT DATE_FORMAT(date, '%M %Y') AS formatted_date
or do it in php (somewhat less efficient):
$formatted = date('F Y', strtotime($row['date']));
回答3:
echo date('F Y', strtotime($row['date']));
回答4:
You can use Datetime:
$date = date_create($row["date"]);
echo date_format($date, 'F Y');
回答5:
you need to use SQL function DATE_FORMAT (date, format)
see this link http://www.w3schools.com/sql/func_date_format.asp
回答6:
If you want to save it as a new variable to be used multiple times:
$datetime = strtotime($row['date']);
$mysqldate = date("M d ", $datetime);
echo $mysqldate;
来源:https://stackoverflow.com/questions/17495547/format-date-within-an-echo