2

How possible to display days with strftime in format 1st, 2nd, 25th, 23rd etc... ?

My current code looks like :

strftime("%B %d, %Y",$expiration_date);

I have checked some solutions, but doesn't work.

Ryan B
  • 3,364
  • 21
  • 35
Zeta
  • 663
  • 1
  • 12
  • 27

2 Answers2

3

If your dates are using timestamps in the background, you can simply format your dates with PHP's date(). It has a format character S doing exactly what you need:

date('jS', $timestamp);

would return something like "1st", "2nd", "3rd" etc.

If you do not use timestamps, olivier's solution is probably your best bet, or turn the dates into timestamps with strtotime(). Dealing with the latter isn't worth it just for this problem, but timestamps are something you should look into if you plan on doing arithmetic operations on dates (such as finding the interval between two dates).

Community
  • 1
  • 1
ljacqu
  • 2,132
  • 1
  • 17
  • 21
0

You can use this function:

<?php

function addOrdinalNumberSuffix($num) {
    if (!in_array(($num % 100), array(11,12,13))) {
        switch ($num % 10) {
            // Handle 1st, 2nd, 3rd
            case 1:  return $num.'st';
            case 2:  return $num.'nd';
            case 3:  return $num.'rd';
        }
    }
    return $num.'th';
}

$expiration_date = time();

$date_str  = strftime("%B ", $expiration_date);
$date_str .= addOrdinalNumberSuffix(strftime("%d", $expiration_date));
$date_str .= strftime(", %Y", $expiration_date);

echo $date_str; // July 18th, 2014

?>

This said, the workaround mentioned by Lightness Races in Orbit in the comments seems nicer to me.

olivier
  • 1,007
  • 8
  • 14