human_readable_duration()
云策文档标注
概述
human_readable_duration() 函数用于将时间持续时间转换为人类可读的格式,支持 HH:ii:ss 或 ii:ss 格式的字符串输入,并可处理负号前缀。函数返回格式化后的字符串或失败时返回 false。
关键要点
- 参数 $duration 必须是字符串,格式为 HH:ii:ss 或 ii:ss,可带负号前缀。
- 返回值为人类可读的持续时间字符串(如“4 hours, 30 minutes, 25 seconds”)或失败时返回 false。
- 函数内部使用正则表达式验证输入格式,并提取小时、分钟、秒部分进行本地化处理。
- 支持国际化,通过 _n() 函数处理单复数形式。
代码示例
// Get duration in human readable format.
$duration = human_readable_duration( '4:30:25' );
echo $duration;
// Output: 4 hours, 30 minutes, 25 seconds注意事项
- 输入字符串必须符合指定格式,否则函数返回 false。
- 负号前缀会被移除,不影响输出格式。
- 函数从 WordPress 5.1.0 版本引入。
原文内容
Converts a duration to human readable format.
Parameters
$durationstringrequired-
Duration will be in string format (HH:ii:ss) OR (ii:ss), with a possible prepended negative sign (-).
Source
function human_readable_duration( $duration = '' ) {
if ( ( empty( $duration ) || ! is_string( $duration ) ) ) {
return false;
}
$duration = trim( $duration );
// Remove prepended negative sign.
if ( str_starts_with( $duration, '-' ) ) {
$duration = substr( $duration, 1 );
}
// Extract duration parts.
$duration_parts = array_reverse( explode( ':', $duration ) );
$duration_count = count( $duration_parts );
$hour = null;
$minute = null;
$second = null;
if ( 3 === $duration_count ) {
// Validate HH:ii:ss duration format.
if ( ! ( (bool) preg_match( '/^([0-9]+):([0-5]?[0-9]):([0-5]?[0-9])$/', $duration ) ) ) {
return false;
}
// Three parts: hours, minutes & seconds.
list( $second, $minute, $hour ) = $duration_parts;
} elseif ( 2 === $duration_count ) {
// Validate ii:ss duration format.
if ( ! ( (bool) preg_match( '/^([0-5]?[0-9]):([0-5]?[0-9])$/', $duration ) ) ) {
return false;
}
// Two parts: minutes & seconds.
list( $second, $minute ) = $duration_parts;
} else {
return false;
}
$human_readable_duration = array();
// Add the hour part to the string.
if ( is_numeric( $hour ) ) {
/* translators: %s: Time duration in hour or hours. */
$human_readable_duration[] = sprintf( _n( '%s hour', '%s hours', $hour ), (int) $hour );
}
// Add the minute part to the string.
if ( is_numeric( $minute ) ) {
/* translators: %s: Time duration in minute or minutes. */
$human_readable_duration[] = sprintf( _n( '%s minute', '%s minutes', $minute ), (int) $minute );
}
// Add the second part to the string.
if ( is_numeric( $second ) ) {
/* translators: %s: Time duration in second or seconds. */
$human_readable_duration[] = sprintf( _n( '%s second', '%s seconds', $second ), (int) $second );
}
return implode( ', ', $human_readable_duration );
}
Changelog
| Version | Description |
|---|---|
| 5.1.0 | Introduced. |
Skip to note 3 content
rabmalin
// Get duration in human readable format. $duration = human_readable_duration( '4:30:25' ); echo $duration;Output:
4 hours, 30 minutes, 25 secondsSkip to note 4 content
mattiasf
// Get duration in human readable format from seconds $seconds = '121'; $duration = human_readable_duration( gmdate( 'H:i:s', $seconds ) ); echo $duration;Output:
0 hours, 2 minutes, 1 second