Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 704
Regis Zaleman Avatar asked Mar 09 '11 14:03

Regis Zaleman


People also ask

What does date () do in PHP?

PHP date() Function The PHP date function is used to format a date or time into a human readable format. It can be used to display the date of article was published. record the last updated a data in a database.

How can I get current date in YYYY MM DD format in PHP?

date_default_timezone_set('UTC'); echo "<strong>Display current date dd/mm/yyyy format </strong>". "<br />"; echo date("d/m/Y"). "<br />"; echo "<strong>Display current date mm/dd/yyyy format</strong> "."<br />"; echo date("m/d/Y")."<br />"; echo "<strong>Display current date mm-dd-yyyy format </strong>".

How do I display the day of the week in PHP?

Use strtotime() function to get the first day of week using PHP. This function returns the default time variable timestamp and then use date() function to convert timestamp date into understandable date. strtotime() Function: The strtotime() function returns the result in timestamp by parsing the time string.

How do I +1 a date in PHP?

php $date = "2022-08-12"; // Add days to date and display it echo date('Y-m-d', strtotime($date. ' +10 days')); // 2022-08-22 echo date('Y-m-d', strtotime(date('Y-m-d'). ' +1 days')); // 2022-08-23 echo date('Y-m-d', strtotime(date('Y-m-d'). ' +1 months')); // 2022-09-12 echo date('Y-m-d', strtotime(date('Y-m-d').


3 Answers

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.

like image 196
acm Avatar answered Nov 15 '22 19:11

acm


This worked for me:

echo date('M j\<\s\u\p\>S\<\/\s\u\p\> Y', $timestamp);
like image 42
Trevor Avatar answered Nov 15 '22 20:11

Trevor


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);
like image 24
Blair McMillan Avatar answered Nov 15 '22 19:11

Blair McMillan