1

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?

1 Answer 1

1

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' );
  }
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.