www.websiteadministrator.com.au/articles/PHP-Tips-Date-Ordinal-Numbers-and-Truncating-Zeros.html
Header

Website Administrator

    Quick PHP Tips for the budding Website Administrator...
 

PHP Date Tips: Ordinal Numbers and Truncating Zeros

Website Administrator Quick PHP Tips

Date display tips: Friday, 23rd June 2017

This is also posted on our blog.

Php and ordinal numbers

Ordinal numbers are inclusive of the letters that appear after the number of the day. Eg. 1st, 2nd, 3rd, 4th etc.

Php already has a feature that will display this for you in it's date handling functions. This is today's example:

Ordinal Example One

This code:
<?php echo date('dS'); ?>

will display this:
23rd

And this is great. You can see that this code will show our ordinal suffix with ease.

But if you are calling this code between the 1st and 9th of the month, there is a leading zero which makes our date date look out of place. This is not how we write our dates in English. 01st, 03rd, etc.

So we want to extract the 0 from the front of these days. And we can do just that if we load the date into a variable and remove any encounter with a zero from the start of the variable. So if we have 0002, we just want the 2, or 06th, we get 6th.

And this is where Php's ltrim function comes in nicely. We can use it to trim anything we want from the start of a variable. We want to get rid of zeros and so we are going to use it to remove any of these that appear on the left (ltrim = left trim).

I like to display my date a certain way, so let's use that in this next example. You can see that the ordinal part of my code [dS] ends up in the second [1] variable. So make sure you point your code to the correct variable [x] in the second line if you change the display sequence. And now here is one way we can get our desired result with ltrim and explode:

Ordinal Example Two

This code:
<?php
$BlitDate = explode(" ", date('l, dS F Y'));
$BlitDate[1]= ltrim($BlitDate[1], "0");
echo "$BlitDate[0] ";
echo "$BlitDate[1] ";
echo "$BlitDate[2] ";
echo "$BlitDate[3] ";
?>


will display this:
Friday, 23rd June 2017

If you are running Php on a local computer, you can change your computer date to test that it works for any given day.

Also, some of you might not want to run this function on the date unless you really need to. After all, most days of the month don't need this trimming at all. So we can add an if statement so that we only run this for the first 9 days of the month like so:

Ordinal Example Three

This code:
<?php
$BlitDate = explode(" ", date('l, dS F Y'));
if ( $BlitDate[1] < 10 ) {$BlitDate[1]= ltrim($BlitDate[1], "0");
}
echo "$BlitDate[0] ";
echo "$BlitDate[1] ";
echo "$BlitDate[2] ";
echo "$BlitDate[3] ";
?>


will display this:
Friday, 23rd June 2017

And we are done, unless you want to download a strict xhml4/.php template with this last piece of code inside.

fin.

| downloads | home | articles index |