首页 » 后端 » PHP » 正文

PHP:一个计算年龄的函数

发布者:站点默认
2011/11/20 浏览数(2,975) 分类:PHP 评论(1)

RT,代码如下:

<?php
function getAge($year,$month,$day){
	$nowYear = date('Y',time());
	$age = $nowYear - $year;
	$nowTimeStamp = strtotime(date('Y').'-'.date('m').'-'.date('d').' 0:0:0');
	$timeStamp = strtotime($year.'-'.$month.'-'.$day.' 0:0:0');
	$nowDayIndex = date('z',$nowTimeStamp); // 今年到第几天了
	$dayIndex    = date('z',$timeStamp); // 出生时是当年的第几天
	if ($nowDayIndex < $dayIndex){
		$age--;
	}
	return $age;
}
$age = getAge(1987,5,2);
?>

JS版:

一看就知道是个phper写的,- -!

// Usage: $age = getAge('1987-5-2');
function getAge(string){
	birthArray = string.split('-');
	year = birthArray[0];
	month = birthArray[1];
	day = birthArray[2];
   nowYear = date('Y',time());
   age = nowYear - year;
   nowTimeStamp = strtotime(date('Y'),date('m'),date('d'),0,0,0);
   timeStamp = strtotime(year,month,day,0,0,0);
   nowDayIndex = date('z',nowTimeStamp); // 今年到第几天了
   dayIndex    = date('z',timeStamp); // 出生时是当年的第几天
   if (nowDayIndex < dayIndex){
      age--;
   }
   return age;
}
function strtotime(Y,m,d,H,i,s){
	var ux = Date.UTC(Y,m,d,H,i,s)/1000;
	return ux;
}
function time(){
	var dt = new Date();
	var ux = Date.UTC(dt.getFullYear(),dt.getMonth(),dt.getDay(),dt.getHours(),dt.getMinutes(),dt.getSeconds())/1000;
	return ux;
}

<完>

点击返回顶部
  1. 留言
  2. 联系方式