Skip to content

Instantly share code, notes, and snippets.

@Lewiscowles1986
Created December 9, 2014 03:43
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 Lewiscowles1986/d458ef211b96ff879d26 to your computer and use it in GitHub Desktop.
Save Lewiscowles1986/d458ef211b96ff879d26 to your computer and use it in GitHub Desktop.
Testing Human date / time
<?php
//
// setup
//
date_default_timezone_set('Europe/London');
//
// code to test
//
$post_time = get_the_time( 'U' );
$human_time = human_time_diff( $post_time, time() );
$cb_date = sprintf(
'<i class="fa fa-clock-o"></i> <time class="updated" datetime="%s">%s ago</time>',
date( 'Y-m-d H:i:s', $post_time ),
$human_time
);
//
// For testing only
//
echo $cb_date; //echo result
//
// Supporting functions
//
function get_the_time( $format ) {
$date = new DateTime('1986-05-21');
return $date->format($format);
}
// human_time_diff
//
// from https://github.com/kluther/Pipeline/blob/master/lib/human_time_diff.php
// #GoogleFu
//
function formatCount($n, $singular, $plural, $none = '0')
{
if ($n == 0) {
return "{$none}&nbsp;{$plural}";
} elseif ($n == 1) {
return "{$n}&nbsp;{$singular}";
} else {
return "{$n}&nbsp;{$plural}";
}
}
function human_time_diff( $from, $to = '' ) {
if ( empty($to) )
$to = time();
$diff = (int) abs($to - $from);
if ($diff <= 3600) {
$mins = round($diff / 60);
if ($mins <= 1) {
$mins = 1;
}
/* translators: min=minute */
$since = formatCount($mins, 'min', 'mins');
} else if (($diff <= 86400) && ($diff > 3600)) {
$hours = round($diff / 3600);
if ($hours <= 1) {
$hours = 1;
}
$since = formatCount($hours, 'hour', 'hours');
} elseif ($diff >= 86400) {
$days = round($diff / 86400);
if ($days <= 1) {
$days = 1;
}
$since = formatCount($days, 'day', 'days');
}
$formatted = (($to-$from) < 0) ? ("in ".$since) : ($since." ago");
return $formatted;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment