gpt4 book ai didi

PHP计算人的当前年龄

转载 作者:可可西里 更新时间:2023-11-01 13:01:58 24 4
gpt4 key购买 nike

我网站上的出生日期格式为 12.01.1980 .

$person_date (string) = Day.Month.Year

想加一个人的故乡。比如“Currently 30 years”(2010 - 1980 = 30 年)。

但是仅仅几年的时间做这个函数并不能给出完美的结果:

如果人的出生日期是 12.12.1980当前日期是 01.01.2010这个人没有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) else if (birth month < current month) { $total_year = $total_year (30); }

4) else if (birth month = current month) { $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计算人的当前年龄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3380990/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com