Most social networks provide a historical timestamp to read as a human-readable string - such as 1 day ago
, 3 weeks ago
, 1 year
, 5 months
, and so on. The same application applies to future events or posts. The purpose of the string is to provide a general frame of time-reference and thus negating the need for any mental acrobatics. WordPress provides a default function called human_time_diff() that accomplishes this from within WordPress. It's this function we've slightly modified for use in other PHP applications (outside of WP).
PHP Code
1
<?php
2
/*
3
Retrieve the plural or single form based on the supplied amount.
4
@param string $single The text that will be used if $number is 1.
5
@param string $plural The text that will be used if $number is not 1.
6
@param int $number The number to compare against to use either $single or $plural.
7
@return string Either $single or $plural translated text.
8
https://core.trac.wordpress.org/browser/tags/4.7.3/src/wp-includes/l10n.php#L361
9
*/
10
11
12
return 1 === $number ? $single : $plural;
13
}
14
15
/*
16
17
Determines the difference between two timestamps.
18
Static Day Countdown with WordPress Shortcode or PHP
19
http://www.beliefmedia.com/static-countdown
20
https://core.trac.wordpress.org/browser/tags/4.8/src/wp-includes/formatting.php#L3216
21
*/
22
23
function beliefmedia_human_time_diff($from, $to = '', $text = false) {
24
25
26
27
28
if ($diff < 3600) {
29
30
if ($mins <= 1)
31
$mins = 1;
32
/* translators: min=minute */
33
34
}
35
elseif ($diff < 86400 && $diff >= 3600) {
36
37
if ($hours <= 1)
38
$hours = 1;
39
40
}
41
elseif ($diff < 604800 && $diff >= 86400) {
42
43
if ($days <= 1)
44
$days = 1;
45
46
}
47
elseif ($diff < 30 * 86400 && $diff >= 604800) {
48
49
if ($weeks <= 1)
50
$weeks = 1;
51
52
}
53
elseif ($diff < 31536000 && $diff >= 30 * 86400) {
54
55
if ($months <= 1)
56
$months = 1;
57
58
}
59
elseif ($diff >= 31536000) {
60
61
if ($years <= 1)
62
$years = 1;
63
64
}
65
66
return ($to - $from > 0) ? $since : $since = ($text !== false) ? $since. ' ago' : $since;
67
}
Examples
Returns: 44 years ago
.
Returns: 6 months
.
Considerations
- The argument of
$text
determines if theago
text is returned. - You may find other variations of this function on our PHP Snippets page.
- See also: Static Day Countdown with WordPress Shortcode or PHP.
- See also: Display Time To Published or Scheduled Posts (WP Snippet).
- The
_n
function is one to essentially nullify the WP translation object.
Download
Title: Human Readable Time Difference With PHP
Description: Human Readable Time Difference With PHP. A modified version of WP's human_time_diff function.
Download • Version 0.2, 1.1K, zip, Category: PHP Code & Snippets