Fix PHP strftime %e on Windows

If you are being bugged by PHP's strftime returning false (printing nothing) when using %e modifier for day of the month on Windows then you are in the right place. It's easy to skip the huge warning red box at the bottom of strftime function page:

Warning: The %e modifier is not supported in the Windows implementation of this function. To achieve this value, the %#d modifier can be used instead.

The solution is simple: if you are using Windows only and will never move to a Linux server (which is unlikely) just change %d for %#e. If you want to make your code work on either system, it's easy to detect the OS using PHP_OS and use the correct modifier. For example, to make $format = '%B %e, %Y' (which gives "August 4, 2013") work on both Windows and Linux you can use:

$format = '%B '.((strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') ? '%#d' : '%e').', %Y';
$formated_date = strftime($format, $unix_timestamp);

This code checks for the OS and uses %e just if it's running on a Windows server.

If you are using %e for several formats it may be easier to create a function to "fix" strftime. Here is the function taken from php.net:

function fixed_strftime($format, $unix_timestamp) {
    if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
         $format = preg_replace('#(?<!%)((?:%%)*)%e#', '\1%#d', $format);
    }
    return strftime($format, $unix_timestamp);
}

One comment

Leave a Reply

Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>