Skip to content

Instantly share code, notes, and snippets.

@benyaminshoham
Created September 21, 2016 08:44
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 benyaminshoham/476ac4caabc41de4e8eb43d7d57dde11 to your computer and use it in GitHub Desktop.
Save benyaminshoham/476ac4caabc41de4e8eb43d7d57dde11 to your computer and use it in GitHub Desktop.
Human-readable (and reasonable) date-time interval format function in PHP.
/**
* Human-readable and reasonable date-time interval formatter
* ----------------------------------------------------------
* Author: Benyamin shoham
* -----------------------
* Format an interval to show existing components in a Human Readable fashion
* If the interval doesn't have a time component (years, months, etc)
* That component won't be displayed.
* You can decide how many components will be displayed (e.g. "1 year 2 months" = 2 components)
* You can select a delimiter to format the interval (e.g. "1 year aaaand 2 months"
*
* Idea is based on source: https://gist.github.com/xadim/8cf3569ee14ec943c324
*
* @param DateInterval $interval - The interval
*
* @param int $max_parts - number of interval parts to return. Default = 2
*
* @param string $delimiter - Inserted after each part, except the last one. Default = ' ' (one space)
*
* @return string Formatted interval string.
*/
function format_reasonable_interval( DateInterval $interval, $max_parts = 2, $delimiter = ' ' ) {
$result = "";
$parts = 0;
$interval_map = [
'year' => [ 'interval' => $interval->y, 'format' => '%y year' ],
'month' => [ 'interval' => $interval->m, 'format' => '%m month' ],
'day' => [ 'interval' => $interval->d, 'format' => '%d day' ],
'hour' => [ 'interval' => $interval->h, 'format' => '%h hour' ],
'minute' => [ 'interval' => $interval->i, 'format' => '%i minute' ],
'second' => [ 'interval' => $interval->s, 'format' => '%s second' ],
];
foreach ( $interval_map as $interval_part ) {
if ( $interval_part['interval'] && $parts < $max_parts ) {
// Format interval part using map.
$result .= $interval->format( $interval_part['format'] );
// Add plural suffix if interval part is larger than 1
// e.g. 1 hour, 3 hours
if ( $interval_part['interval'] > 1 ) {
$result .= 's';
}
// Add delimiter after all parts except the last one.
if ( $parts < $max_parts - 1 ) {
$result .= $delimiter;
}
$parts ++;
}
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment