At least once in your life you have seen a site that has limited time offers, or memberships that expires on a specific date.
If you noticed, they often say “Expires in X”. That’s easy to understand for a human, but how do you do it in WordPress?
Ideally you would have timestamps saved in your database or generated at the moment, instead of human readable dates. Timestamps for a human are impossible to read since they show the seconds since January 1st 1970 (UTC). For example, the current timestamp is 1471946578. Would you be able to tell what is the date by reading that? Obviously no.
When you have two timestamps and want to make a time difference between them, you also would want to show it in a readable format for humans.
human_time_diff is a WordPress function that allows you to show a time difference in a human readable format.
You would use
human_time_diff by writing something like this:
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
|// Difference for between now and a date in the future|
|$future_timestamp = strtotime( '1st January 2020' );|
|$difference = human_time_diff( current_time( 'timestamp' ), $future_timestamp );|
|// Difference between a date in the past and now|
|$past_timestamp = strtotime( '1st January 2016' );|
|$difference = human_time_diff( $past_timestamp, current_time( 'timestamp' ) );|
Note that the order of arguments passed to the function is always from and to.
In the first example above, I compare a date in the future against the current date, so I use the current timestamp as first argument.
In the second example, I compare a date in the past against the current date, so the first argument would be the past date, and then the current timestamp.