Saturday 2 April 2011

Php tip - how to explode time and get rid of the 0s and add an ordinal sufix

When displaying time, i like to have 1, 2, 3 etc. No zeros. Not only that, i like the ordinals. So i want 1st, 2nd, 4th etc.

So i was plying with php again today and figured this to be a simple way out, there may be other ways, but this one works just fine (Here is a live working demo of this with the same code to copy and paste if you prefer to see it in action too.)

First we work out what we want to display eg. this is my favorite:
<?php echo date('l, dS F Y'); ?>

And that takes care of most of it, except for the first nine days of the month where we get 01st, 02nd, 08th etc. and that makes us feel pretty ordinary about our ordinals.

So, second, lets lop off those zeros. Explode and using ltrim on the 2nd variable in our new explode array fixes that if we tell it to expunge any 0s. Then ltrim will go into action and fix our 01st-09th days and so...

<?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] ";
?>

You can run an if instruction if you want to only run ltrim on the first several days of the month like so..
<?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] ";
?>

they both smell of roses and you're all fixed up and ready to go again!

No comments:

Post a Comment

Important Note:

Anyone is free to post links here but only if a back link to this site (or www.websiteadministrator.com.au) is added from your blog or website.