PHP计算人的当前年龄

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了PHP计算人的当前年龄脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我的网站上有出生日期,格式为12.01.1980.
$PErson_date (string) = Day.Month.Year

想要添加一个人的故乡.像“目前30年”(2010年 – 1980年= 30年​​).

但是几年来的功能不能给出完美的结果:

如果出生日期是1980年12月12日,当前日期是2010年1月1日,那么该人没有30岁.这是29年零一个月.

必须对出生年份,月份和出生日期进行计算,并与当前日期进行比较:

0)解析日期.

Birth date (Day.Month.Year):
Day = $birth_day;
Month = $birth_month;
Year = $birth_year;

current date (Day.Month.Year):
Day = $current_day;
Month = $current_month;
Year = $current_year;

1)年份比较,2010年 – 1980年=写“30”(让它为$total_year变量)

2)比较月份,如果(出生日期月份大于>当前月份(如出生时12和01当前)){减去一年,从$total_year变量(30 – 1 = 29)}.如果发生减号,则在此时完成计算.否则进入下一步(3步).

3)否则if(出生月份<当月){$total_year = $total_year(30); } 4)否则if(出生月份=当月){$total_year = $total_year(30); } 并查看当天(在此步骤中):

if(birth day = current day) { $total_year = $total_year; }
 else if (birth day > current day) { $total_year = $total_year -1; }
 else if (birth day < current day) { $total_year = $total_year; }

5)echo $total_year;

我的PHP知识不好,希望你能帮忙.

谢谢.

您可以使用 DateTime class及其 diff()方法.
<?PHP
$bday = new DateTime('12.12.1980');
// $today = new DateTime('00:00:00'); - use this for the current date
$today = new DateTime('2010-08-01 00:00:00'); // for testing purposes

$diff = $today->diff($bday);

PRintf('%d years,%d month,%d days',$diff->y,$diff->;m,$diff->d);

打印29年,7个月,20天

脚本宝典总结

以上是脚本宝典为你收集整理的PHP计算人的当前年龄全部内容,希望文章能够帮你解决PHP计算人的当前年龄所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。