Skip to content

Instantly share code, notes, and snippets.

@kovshenin
Created October 2, 2014 15:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kovshenin/a082d06702beb707f606 to your computer and use it in GitHub Desktop.
Save kovshenin/a082d06702beb707f606 to your computer and use it in GitHub Desktop.
Natural time
<?php
function wp_natural_time( $timestamp, $limit = 2 ) {
$from = time();
$diff = absint( $from - $timestamp );
if ( $diff < 1 )
return _x( 'now', 'time ago' );
$result = array();
$l10n = array(
array( YEAR_IN_SECONDS, _nx_noop( '%s year', '%s years', 'time ago' ) ),
array( 30 * DAY_IN_SECONDS, _nx_noop( '%s month', '%s months', 'time ago' ) ),
array( WEEK_IN_SECONDS, _nx_noop( '%s week', '%s weeks', 'time ago' ) ),
array( DAY_IN_SECONDS, _nx_noop( '%s day', '%s days', 'time ago' ) ),
array( HOUR_IN_SECONDS, _nx_noop( '%s hour', '%s hours', 'time ago' ) ),
array( MINUTE_IN_SECONDS, _nx_noop( '%s minute', '%s minutes', 'time ago' ) ),
array( 1, _nx_noop( '%s second', '%s seconds', 'time ago' ) ),
);
foreach ( $l10n as $key => $pair ) {
$count = (int) ( $diff / $pair[0] );
if ( $count > 0 ) {
$result[] = sprintf( translate_nooped_plural( $l10n[ $key ][1], $count ), $count );
$diff -= $count * $pair[0];
}
if ( $limit && count( $result ) >= $limit ) {
break;
}
}
$label = ( $from > $timestamp ) ? _x( '%s ago', 'time ago' ) : _x( '%s from now', 'time from now' );
$result = implode( _x( ', ', 'natural time separator' ), $result );
$result = sprintf( $label, $result );
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment