The human_time_diff() WordPress PHP function determines the difference between two timestamps and returns it in a human-readable format such as “1 hour”, “5 mins”, or “2 days”.
Usage
echo human_time_diff( $from, $to );
Input:
$from
: Unix timestamp from which the difference begins.$to
: Unix timestamp to end the time difference (optional, defaults to current time if not set).
Output:
- A string with a human-readable time difference.
Parameters
$from
(int) – Required. Unix timestamp from which the difference begins.$to
(int) – Optional. Unix timestamp to end the time difference. Default becomestime()
if not set.
More information
See WordPress Developer Resources: human_time_diff
Examples
Displaying the time difference between post creation and last modification
// Get posted and last modified time $lastmodified = get_the_modified_time('U'); $posted = get_the_time('U'); // Display the time difference echo "Posted " . human_time_diff($posted, current_time('U')) . " ago<br>"; if ($lastmodified > $posted) { echo "Edited " . human_time_diff($lastmodified, current_time('U')) . " ago"; }
Displaying the time since a post was published
echo esc_html(human_time_diff(get_the_time('U'), current_time('timestamp'))) . " ago";
Internationalized version of the time since a post was published
printf(_x('%1$s ago', '%2$s = human-readable time difference', 'wpdocs_textdomain'), human_time_diff(get_the_time('U'), current_time('timestamp')));
Displaying the time since a post was last modified
printf(esc_html__('%s ago', 'textdomain'), human_time_diff(get_the_modified_time('U'), strtotime(wp_date('Y-m-d H:i:s'))));
Displaying the time since a comment was posted
printf(_x('%1$s ago', '%2$s = human-readable time difference', 'wpdocs_textdomain'), human_time_diff(get_comment_time('U'), current_time('timestamp')));