Skip to content
Advertisement

Display date with ordinal suffix in PHP

I am currently displaying date in my php code like below

$date = $news_row['date'];
$newDate = date("l M d Y", strtotime($date));

its giving me output like

Monday Mar 08 2021

Instead I want output like

Monday Mar 08th 2021

I have found function

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];
}

on this answer

But I am not getting idea how I can use it with my date format. Let me know if anyone here can help me for do it.

Thanks a lot!

Advertisement

Answer

You can specify any character that you want:

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

But if you want to get 1st, 2nd, 3rd, 4th ... you should use:

$newDate = date("l M jS Y", strtotime($date));
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement