gpt4 book ai didi

php - 从日期计算年份

转载 作者:IT王子 更新时间:2023-10-28 23:57:41 26 4
gpt4 key购买 nike

我正在寻找一个函数,该函数可以从以下格式的日期计算年份:0000-00-00。找到了这个函数,但是它不会工作。

// Calculate the age from a given birth date
// Example: GetAge("1986-06-18");
function getAge($Birthdate)
{
// Explode the date into meaningful variables
list($BirthYear,$BirthMonth,$BirthDay) = explode("-", $Birthdate);
// Find the differences
$YearDiff = date("Y") - $BirthYear;
$MonthDiff = date("m") - $BirthMonth;
$DayDiff = date("d") - $BirthDay;
// If the birthday has not occured this year
if ($DayDiff < 0 || $MonthDiff < 0)
$YearDiff--;
}

echo getAge('1990-04-04');

什么都不输出:/
我有错误报告,但我没有收到任何错误

最佳答案

您的代码不起作用,因为该函数未返回任何要打印的内容。

就算法而言,这个怎么样:

function getAge($then) {
$then_ts = strtotime($then);
$then_year = date('Y', $then_ts);
$age = date('Y') - $then_year;
if(strtotime('+' . $age . ' years', $then_ts) > time()) $age--;
return $age;
}
print getAge('1990-04-04'); // 19
print getAge('1990-08-04'); // 18, birthday hasn't happened yet

这是与接受的答案相同的算法(仅在 PHP 中)in this question .

更简单的方法:

function getAge($then) {
$then = date('Ymd', strtotime($then));
$diff = date('Ymd') - $then;
return substr($diff, 0, -4);
}

关于php - 从日期计算年份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1112835/

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