How to render a time-of-day string like '16:42' with a site's chosen time format?

I have a need to display a time-of-day value in a site's chosen time format.

For example I have 16:42:18 and want to display it as 4:42 PM if the time_format option is g:i A, or 16:42:18 if the time_format is H:i:s.

I need this to render data captured by HTML5's input type=time form field.

How to do this?

Topic localization date-time plugin-development theme-development Wordpress

Category Web


The trick here is using wp_date() in a peculiar way, giving it the time of day in seconds (as if it were 1970-01-01 16:42:18), then asking for it to be formatted in UTC.

$time = '16:42:18';
if ( preg_match( '/^\d\d:\d\d:\d\d$/', $time ) ) {    //validate the $time
  $ts =  intval( substr( $time, 0, 2 ) ) * 3600;
  $ts += intval( substr( $time, 3, 2 ) ) * 60;
  $ts += intval( substr( $time, 7, 2 ) );
  if ( $ts >= 0 && $ts < 86400 ) {
     $time = wp_date( get_option( 'time_format' ), $ts, 'UTC' );
  }
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.