// 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 возвращает «rd» для каждого числа, оканчивающегося на 1 и 2.
Я создал функцию для изменения заданной даты Y-m-d, например: 2016-07-02, на этот формат: 2 июля. [b]Код[/b]:
[code]// 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"; } [/code]
Функция работает должным образом, но есть одна загвоздка. Первый условный тернарный оператор для $subscript возвращает «rd» для каждого числа, оканчивающегося на 1 и 2.
Пример:
[code]echo format_date("2016-01-01"); // It will output January 1rd [/code]