加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP计算人的当前年龄

发布时间:2020-12-13 17:53:15 所属栏目:PHP教程 来源:网络整理
导读:我的网站上有出生日期,格式为12.01.1980. $person_date (string) = Day.Month.Year 想要添加一个人的故乡.像“目前30年”(2010年 – 1980年= 30年??). 但是几年来的功能不能给出完美的结果: 如果出生日期是1980年12月12日,当前日期是2010年1月1日,那么该人
我的网站上有出生日期,格式为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天

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读