PHP: formatting suffix for number of days in php with date ()

I feel a little silly for this, but is there a more elegant way to format the day suffix (st, th), other than calling date () 3 times?

What am I trying to output in html:

<p>January, 1<sup>st</sup>, 2011</p> 

What am I doing now (very hard) in php:

 //I am omitting the <p> tags: echo date('M j',$timestamp) . '<sup>' . date('S', $timestamp) . '</sup>' . date(' Y', $timestamp); 

Does anyone know a better way?

+8
date php formatting
source share
3 answers

You just need to avoid characters that are interpreted by the date function.

 echo date('M j<\sup>S</\sup> Y'); // < PHP 5.2.2 echo date('M j<\s\up>S</\s\up> Y'); // >= PHP 5.2.2 

In the PHP date documentation , you have a list with all the characters replaced by their special value.

+11
source share

This worked for me:

 echo date('M j\<\s\u\p\>S\<\/\s\u\p\> Y', $timestamp); 
+12
source share

I believe that the date function allows you to insert any string you need, provided that you avoid all characters in the format.

 echo date('M j<\s\up>S<\/\s\up> Y', $timestamp); 
+1
source share

All Articles