Time Ago

เกรียนเล่น facebook

เห็นใน facebook เวลา comment หรือว่าทำอะไรแทนที่มันจะแสดงออกมาเป็น datetime เลย มันทำเป็น time ago เลยแหะ
ต้องหัดทำบ้าง…คนที่ office ชอบบอกว่า

จะเอาแบบ facebook อะทำได้มั้ย

แกะ facebook ได้ html

<abbr title=”Tue, 23 Feb 2010 01:52:11 -0800″>17 minutes ago</abbr>

อธิบายวิธีคิดสั้นละกันครับ

  1. เวลาที่ต้องการคำนวน Tue, 23 Feb 2010 01:52:11 -0800 … แปลงให้เป็น timestamp ด้วย strtotime()
  2. เวลาปัจจุบันใช้ time()
  3. ส่วนต่างเวลา diff = time() – strtotime(‘Tue, 23 Feb 2010 01:52:11 -0800′);
  4. คำนวนอายุ … ได้ diff กับ periods โอย..ไปแกะเองเหอะพี่น้อง
  5. diff ปัดเศษ
  6. return diff periods ago

code PHP

function ago($time) {
$periods = array(“second”, “minute”, “hour”, “day”, “week”, “month”, “year”, “decade”);
$lengths = array(“60″,”60″,”24″,”7″,”4.35″,”12″,”10″);

$now = time();

$difference = $now – $time;
$tense      = “ago”;

for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
$difference /= $lengths[$j];
}
$difference = round($difference);
$period = ($difference != 1) ? $periods[$j].’s’ : $periods[$j];
return “$difference $period $tense”;
}

เรียกใช้

echo ago(strtotime(‘Mon, 22 Feb 2010 17:28:12 -0800′)). “\n”;
echo ago(strtotime(’2010-02-23 17:30:00′)). “\n”;
echo ago(strtotime(’2010-02-23 17:48:00′)). “\n”;

มันยังไม่จบครับพี่น้องมี jquery version ด้วย…รอก่อน


3 responses so far, want to say something?

  1. LookHin says:

    โอเจ แจ่ม เดียวเอาไปใช้บ้าง

  2. กาก้า says:

    สุดยอดอีกแล้วครับ เฮีย ^____^

  3. linksys says:

    คือ tag อะไรครับ ไม่เคยเห็น

Leave a Reply