Regis Zaleman
Regis Zaleman

Reputation: 3250

PHP: Formatting the day number suffix in php with date()

I feel a bit silly for this one, but is there a more elegant way to format the day number suffix (st, th) other than by having to call the date() 3 times?

What I am trying to output in html:

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

What I am doing now (feels very heavy) in php:

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

Anyone knows a better way?

Upvotes: 11

Views: 12021

Answers (3)

acm
acm

Reputation: 6637

You just have to escape 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

At PHP date documentation you have a list with all characters replaced by their special meaning.

Upvotes: 26

Blair McMillan
Blair McMillan

Reputation: 5349

I believe the date function allows you to put in any string that you want, provided that you escape all format characters.

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

Upvotes: 2

Trevor
Trevor

Reputation: 60230

This worked for me:

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

Upvotes: 14

Related Questions