Formatting PHP Date() Time Strings with AP Style

While developing an event management application, I ran into an interesting challenge: we use Associated Press (AP) Style for our Web publications, but PHP’s date() function only support time suffixes “am / pm” or “AM / PM”. AP Style calls for times to be formatted with “a.m. / p.m.”

To solve the problem, I came up with the following function:

CODE

<?php

function APtime($timestring){

$APstyleTime = (str_replace(array(“am”,”pm”,”AM”,”PM”), array(“a.m.”, “p.m.”,”a.m.”, “p.m.”), $timestring));
return $APstyleTime;
}

$myTime = ’12:04 pm’;

echo APtime(date(“g:i a”, strtotime(“$myTime”)));

?>

 

OUTPUT

12:04 p.m.

I’m not a big fan of PHP’s support of date/time formats and masks, but at least this is a simple (and reusable) solution to an annoying problem.

 

Leave a Reply