ตัวอย่างโค้ด
<?php
function to_time_ago($time) {
$difference = time() - $time;
if ($difference < 1) {
return 'less than a second ago';
}
$time_rules = [
12 * 30 * 24 * 60 * 60 => 'year',
30 * 24 * 60 * 60 => 'month',
24 * 60 * 60 => 'day',
60 * 60 => 'hour',
60 => 'minute',
1 => 'second'
];
foreach ($time_rules as $seconds => $unit) {
$res = $difference / $seconds;
if ($res >= 1) {
$t = (int)round($res);
return $t . ' ' . $unit . ($t > 1 ? 's' : '') . ' ago';
}
}
}
echo "The timestamp to time ago conversion is " . to_time_ago(time() - 600);
?>
ผลลัพธ์
The timestamp to time ago conversion is 10 minutes ago
คำอธิบาย
- คำนวณ Difference ระหว่าง Now และ Timestamp ที่ให้มา
- Loop ผ่าน Time Rules (Year → Second)
- หา Unit ใหญ่สุดที่ Difference มากกว่าหรือเท่า 1
- Round และ Format Output
Improved Version (Accurate Months/Years)
ใช้ DateTime Diff สำหรับ Accuracy ดีกว่า (Months มี 28-31 วัน, Years มี Leap Years):
<?php
function time_ago_accurate($timestamp) {
$now = new DateTime();
$then = new DateTime("@$timestamp");
$diff = $now->diff($then);
if ($diff->y > 0) return $diff->y . ' year' . ($diff->y > 1 ? 's' : '') . ' ago';
if ($diff->m > 0) return $diff->m . ' month' . ($diff->m > 1 ? 's' : '') . ' ago';
if ($diff->d > 0) return $diff->d . ' day' . ($diff->d > 1 ? 's' : '') . ' ago';
if ($diff->h > 0) return $diff->h . ' hour' . ($diff->h > 1 ? 's' : '') . ' ago';
if ($diff->i > 0) return $diff->i . ' minute' . ($diff->i > 1 ? 's' : '') . ' ago';
return $diff->s . ' second' . ($diff->s > 1 ? 's' : '') . ' ago';
}
echo time_ago_accurate(time() - 600); // 10 minutes ago
?>
Thai Language Version
<?php
function time_ago_thai($timestamp) {
$now = new DateTime();
$then = new DateTime("@$timestamp");
$diff = $now->diff($then);
$units = [
'y' => ['year', 'ปี'],
'm' => ['month', 'เดือน'],
'd' => ['day', 'วัน'],
'h' => ['hour', 'ชั่วโมง'],
'i' => ['minute', 'นาที'],
's' => ['second', 'วินาที'],
];
foreach ($units as $key => [$en, $th]) {
if ($diff->$key > 0) {
return $diff->$key . ' ' . $th . ' ที่แล้ว';
}
}
return 'เพิ่งเมื่อกี้';
}
echo time_ago_thai(time() - 3661); // 1 ชั่วโมง 1 นาที 1 วินาที ที่แล้ว
?>