【发布时间】:2016-11-04 19:48:45
【问题描述】:
我已经构建了一个函数来将给定的Y-m-d 日期如下:2016-07-02 更改为这种格式:July 2nd。
代码:
// Format the given Y-M-D date
function format_date($date) {
// Parse the date
list($year, $month, $day) = array_values(date_parse($date));
// Give the appropriate subscript to the day number
$last_char = substr($day, -1);
$pre_last_char = (strlen($day) > 1) ? substr($day, -2, -1) : null;
$subscript = ($last_char === "1") ? "st" :
($last_char === "2") ? "nd" :
($last_char === "3") ? "rd" : "th";
$subscript = ($pre_last_char === "1") ? "th" : $subscript;
$day .= $subscript;
// Get the month's name based on its number
$months = [
"1" => "January",
"2" => "February",
"3" => "March",
"4" => "April",
"5" => "May",
"6" => "June",
"7" => "July",
"8" => "August",
"9" => "September",
"10" => "October",
"11" => "November",
"12" => "December"
];
$month = $months[$month];
// Omit the year if it's this year and assemble the date
return $date = ($year === date("Y")) ? "$month $day $year" : "$month $day";
}
该功能按预期工作,但有一个问题。 $subscript 的第一个条件三元运算符为每个以 1 和 2 结尾的数字返回 "rd"。
例子:
echo format_date("2016-01-01"); // It will output January 1rd
我该如何解决这个问题?
【问题讨论】:
-
使用
daysuf -
如果您只想修复您的代码,take a look。检查单行版本以获得更好的视觉效果,了解我打开/关闭的位置(和)。
-
谢谢@FirstOne。我检查了你的修复。我将编辑这个问题以帮助将来可能偶然发现它的任何人。
标签: php ternary-operator