Skip to content

Instantly share code, notes, and snippets.

@JulioPotier
Created February 27, 2020 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JulioPotier/effb228e271c3cda49563cf77655edd9 to your computer and use it in GitHub Desktop.
Save JulioPotier/effb228e271c3cda49563cf77655edd9 to your computer and use it in GitHub Desktop.
function julio_readable_duration( $entry ) {
if ( ! is_numeric( $entry ) ) {
$coeff = [ 1, MINUTE_IN_SECONDS, HOUR_IN_SECONDS, DAY_IN_SECONDS, MONTH_IN_SECONDS, YEAR_IN_SECONDS ];
$data = array_reverse( array_map( 'intval', explode( ':', $entry ) ) );
$entry = 0;
foreach ( $data as $index => $time ) {
$entry += $time * $coeff[ $index ];
}
if ( ! $entry ) {
trigger_error( 'Entry data must be numeric or respect format dd:hh:mm:ss' );
return;
}
}
$from = new \DateTime( '@0' );
$to = new \DateTime( "@$entry" );
$data = explode( ':', $from->diff( $to )->format('%s:%i:%h:%d:%m:%y') );
$return = [];
$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' ),
];
foreach( $data as $i => $time ) {
$return[] = sprintf( translate_nooped_plural( $labels[ $i ], $time ), $time );
}
$return = array_reverse( $return );
$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