Created
December 9, 2014 03:43
-
-
Save Lewiscowles1986/d458ef211b96ff879d26 to your computer and use it in GitHub Desktop.
Testing Human date / time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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} {$plural}"; | |
} elseif ($n == 1) { | |
return "{$n} {$singular}"; | |
} else { | |
return "{$n} {$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