Calculate Age By PHP คำนวนอายุด้วย PHP (JS+PHP)

Calculate Age By PHP Calculate Age By PHP คำนวนอายุด้วย PHP
เป็นฟังก์ชันที่ใช้ใช้งานค่อนข้างบ่อยสำหรับนักพัฒนาระบบ ซึ่งฟังก์นี้สามารถนำไปงานได้เลย เพียงแค่รับวันที่ๆ จะคำนวน ก็ฟังก์ชันก็จะคำนวนให้อัตโนมัติเลยตัวนี้





Code (PHP)
01.<?php
02.$dateofbirth = "1987-05-16";
03./*
04.Calculate age for details
05.*/
06. 
07.function getAges($dateofbirth) {
08. 
09.$today = date("Y-m-d");
10./*
11.function
12.list : Assign variables as if they were an array.
13.explode : Break a string into an array.
14.*/
15.list($byears, $bmonth, $bday) = explode("-", $dateofbirth);
16.list($tyears, $tmonth, $tday) = explode("-", $today);
17. 
18.if($byears < 1970) {
19.$yearad = 1970 - $byears;
20.$byears = 1970;
21.}else {
22.$yearad = 0;
23.}
24. 
25.$mbirth = mktime(0,0,0, $bmonth, $bday, $byears);
26.$mtoday = mktime(0,0,0, $tmonth, $tday, $tyears);
27. 
28.$mage = ($mtoday - $mbirth);
29.$wyears = (date("Y", $mage)-1970+$yearad);
30.$wmonths = (date("m", $mage)-1);
31.$wdays = (date("d", $mage)-1);
32. 
33.$ystr = ($wyears > 1 ? " YEARS" : " YEAR");
34.$mstr = ($wmonths > 1 ? " MONTHS" : " MONTH");
35.$dstr = ($wdays > 1 ? " DAYS" : " DAY");
36. 
37.if($wyears > 0 && $wmonths > 0 && $wdays > 0) {
38.$agestr = $wyears.$ystr." ".$wmonths.$mstr." ".$wdays.$dstr;
39.}else if($wyears == 0 && $wmonths == 0 && $wdays > 0) {
40.$agestr = $wdays.$dstr;
41.}else if($wyears > 0 && $wmonths > 0 && $wdays == 0) {
42.$agestr = $wyears.$ystr." ".$wmonths.$mstr;
43.}else if($wyears == 0 && $wmonths > 0 && $wdays > 0) {
44.$agestr = $wmonths.$mstr." ".$wdays.$dstr;
45.}else if($wyears > 0 && $wmonths == 0 && $wdays > 0) {
46.$agestr = $wyears.$ystr." ".$wdays.$dstr;
47.}else if($wyears == 0 && $wmonths > 0 && $wdays == 0) {
48.$agestr = $wmonths.$mstr;
49.}else {
50.$agestr ="";
51.}
52. 
53.return $agestr;
54.}
55. 
56.echo getAges($dateofbirth);


Credit by : http://www.ubu.ac.th/ocn_blog/blog/buncha-37
Modify By : DEVPOP