Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.