This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function julio_readable_duration( $entry, $with_zeros = 'all', $first_caps = false ) { | |
// If we use the human_readable_duration format with ":" | |
if ( ! is_numeric( $entry ) ) { | |
// Create coefficients to get the real seconds count since 1970 | |
$coeff = [ 1, MINUTE_IN_SECONDS, HOUR_IN_SECONDS, DAY_IN_SECONDS, MONTH_IN_SECONDS, YEAR_IN_SECONDS ]; | |
// we start from seconds to years and keep only integer values | |
$data = array_reverse( array_map( 'intval', explode( ':', $entry ) ) ); | |
// we reset the $entry param | |
$entry = 0; | |
// Now for each of our data, we multiply using the next coeff at each iteration | |
foreach ( $data as $index => $time ) { | |
$entry += $time * $coeff[ $index ]; | |
} | |
// Now we should have a number of second, or… you were using a text! -> notice and stop | |
if ( ! $entry ) { | |
trigger_error( 'Entry data must be numeric or respect format dd:hh:mm:ss' ); | |
return; | |
} | |
} | |
// Transform the seconds into a full param string from seconds to years (max 999) | |
$from = new \DateTime( '@0' ); | |
$to = new \DateTime( "@$entry" ); | |
$data = explode( ':', $from->diff( $to )->format('%s:%i:%h:%d:%m:%y') ); | |
// This is where we will add our results to be returned | |
$return = []; | |
// Native labels from WP, yipikaye! | |
$labels = [ _n_noop( '%s second', '%s seconds' ), | |
_n_noop( '%s minute', '%s minutes' ), | |
_n_noop( '%s hour', '%s hours' ), | |
_n_noop( '%s day', '%s days' ), | |
_n_noop( '%s month', '%s months' ), | |
_n_noop( '%s year', '%s years' ), | |
]; | |
// Now again for each value, we get the correct plural form | |
foreach( $data as $i => $time ) { | |
// We can display the zeros or not, ot just the last ones (see examples) | |
if ( '0' === $time && ( 'none' === $with_zeros || ( 'last' === $with_zeros && ! empty( array_filter( $return, 'intval' ) ) ) ) ) { | |
continue; | |
} | |
// The translated string | |
$tmp = sprintf( translate_nooped_plural( $labels[ $i ], $time ), $time ); | |
// We can get first letter of day in caps (like in english) | |
if ( $first_caps ) { | |
$tmp = ucwords( $tmp ); | |
} | |
// Add this in our results… | |
$return[] = $tmp; | |
} | |
// … but we need it from years to seconds now | |
$return = array_reverse( $return ); | |
// And use the magic wp_sprintf_l to get the ',' and ', and' ! | |
$text = wp_sprintf( '%l', $return ); | |
return $text; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment