计算从日期开始的年数 [英] Calculate years from date

查看:153
本文介绍了计算从日期开始的年数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种以格式计算年数的函数:0000-00-00。
发现这个功能,但它不会工作。

I'm looking for a function that calculates years from a date in format: 0000-00-00. Found this function, but it wont work.

// 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');

没有输出:/

i有错误报告,但我没有收到任何错误

outputs nothing :/
i have error reporting on but i dont get any errors

推荐答案

您的代码无效,因为该功能没有返回任何要打印的内容。

Your code doesn't work because the function is not returning anything to print.

就算法而言,如何做:

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中)接受的答案是此问题

This is the same algorithm (just in PHP) as the accepted answer in this question.

一个较短的方法:

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

这篇关于计算从日期开始的年数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆