在PHP中显示带序数后缀的日期

5
我目前在我的php代码中以以下方式显示日期:
$date = $news_row['date'];
$newDate = date("l M d Y", strtotime($date));

它给我输出结果如下:

2021年3月8日星期一

但我想要输出结果如下:

2021年3月8日星期一

我已经找到了以下函数:

function ordinal($number) {
    $ends = array('th','st','nd','rd','th','th','th','th','th','th');
    if ((($number % 100) >= 11) && (($number%100) <= 13))
        return $number. 'th';
    else
        return $number. $ends[$number % 10];
}

在这个答案中:

但是我不知道如何将它与我的日期格式一起使用。如果有人能帮我做到这一点,请告诉我。

非常感谢!

2个回答

5
$newDate = date('l M jS Y', strtotime($date));

阅读有关PHP中更多日期时间格式的信息

https://www.php.net/manual/zh/datetime.format.php

l => A full textual representation of the day of the week

M=> A short textual representation of a month, three letters, 

j => Day of the month without leading zeros

S => English ordinal suffix for the day of the month, 2 characters

Y => A full numeric representation of a year, 4 digits

1
谢谢!我已经点赞了,由于Amir已经给出了正确的答案,我不能多次接受它。谢谢! - Mira

3
您可以指定任何您想要的字符:
$newDate = date("l M d\t\h Y", strtotime($date));

但如果您想获取 第1、第2、第3、第4... ,您应该使用:

$newDate = date("l M jS Y", strtotime($date));

但它将始终是th,我想要动态的,可以根据问题中给出的函数变为th、st和nd等。谢谢! - Mira
@Mira,你在问题中没有指明这一点! - Amir MB
哇!太棒了!没有使用那个函数,它就像魔法一样工作。非常感谢! - Mira

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接