Convert a 24hr number to time in a WordPress shortcode

Viewed 24

I'm trying to take a 4-digit number (e.g. 0900) and convert it into a time. I took the route of just formatting the number and adding the colon, which worked fine until I realized that needed to be output in 12hr with the am/pm. I'm wrapping the function in a WordPress shortcode to use it for a custom field output.

function hel_format_time($atts, $content = null) {
    $content = do_shortcode($content);
    $time = substr_replace($content, ':', 2, 0);
    return $time;
}
add_shortcode('format-time', 'hel_format_time');

This will translate the content of 0900 into 09:00 but what I need is 0900 into 9:00 am.

1 Answers

It looks like you are trying to convert army time into am/pm format. If that is the case, please! try this.

function hel_format_time($atts, $content = null) {
    $content = do_shortcode($content);
    $time = date("h:i a", strtotime($content));
    return $time;
}
add_shortcode('format-time', 'hel_format_time');

Thanks

Related