Display date with ordinal suffix in PHP

Viewed 498

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!

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

Read about more datetime formats in PHP

https://www.php.net/manual/en/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

You can specify any character that you want:

$newDate = date("l M d\t\h Y", strtotime($date));

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

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