Menampilkan Tanggal Relatif di WordPress

Tanggal relatif di sini misalnya “7 days ago” atau “10 minutes ago”.

Untuk menampilkan tanggal semacam itu di WordPress, sebenarnya sudah ada fungsi bawaan WP, yaitu human_time_diff(). Seperti dibahas oleh seorang teman di sini. 😉

Tapi sayangnya, fungsi tersebut belum lengkap. Hanya bisa sampai menit, jam, dan hari saja.

Maka cara lain supaya bisa menampilkan hingga tahun, bisa menggunakan fungsi time_since() berikut ini.

[php]
function time_since($older_date, $newer_date = false) {
$chunks = array(
‘year’ => 60 * 60 * 24 * 365,
‘month’ => 60 * 60 * 24 * 30,
‘week’ => 60 * 60 * 24 * 7,
‘day’ => 60 * 60 * 24,
‘hour’ => 60 * 60,
‘minute’ => 60,
‘second’ => 1
);

$newer_date = ($newer_date == false) ? (time()+(60*60*get_option(“gmt_offset”))) : $newer_date;
$since = $newer_date – $older_date;

foreach ($chunks as $key => $seconds)
if (($count = floor($since / $seconds)) != 0) break;

$messages = array(
‘year’ => _n(‘%s year ago’, ‘%s years ago’, $count),
‘month’ => _n(‘%s month ago’, ‘%s months ago’, $count),
‘week’ => _n(‘%s week ago’, ‘%s weeks ago’, $count),
‘day’ => _n(‘%s day ago’, ‘%s days ago’, $count),
‘hour’ => _n(‘%s hour ago’, ‘%s hours ago’, $count),
‘minute’ => _n(‘%s minute ago’, ‘%s minutes ago’, $count),
‘second’ => _n(‘%s second ago’, ‘%s seconds ago’, $count),
);
return sprintf($messages[$key],$count);
}
[/php]

Cara penggunaannya, misal dalam loop the_post():

[php]
echo time_since(get_the_time(‘U’), current_time(‘timestamp’));
[/php]

Semoga bermanfaat. 🙂

Sumber: WordPress Answers – Relative Time On Posts

Published by Eric Gunawan

Happiness Engineer. WordPress Ambassador. Remote Worker. Soccer News Follower. Movie Lover. Proud Father. Lucky Husband.

One thought on “Menampilkan Tanggal Relatif di WordPress

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: