1

我之前问过这个问题并接受了答案,但现在我发现我们服务器上的 php 版本是 5.2 并且DateTime::diff()无法正常工作。

我想使用出生日期和给定日期计算人的年龄(以月加天为单位)。

日期格式输入: Ymd(例如:1986-08-23)

输出:

5 months and 20 days old.
150 months and 4 days old.
285 months and 30 days old.

谢谢

4

2 回答 2

5

这是一个可以准确确定月数和天数(包括闰年)的解决方案。它假设 7 月 21 日到 8 月 21 日是 1 个月 0 天,而不是 1 个月 1 天,并且 3 月 21 日到 4 月 20 日是 0 个月 30 天,而不是 1 个月 0 天。在这两种情况下,后者都是当您直接除以 30 来计算月份时发生的情况。

我确信有更好的方法来优化功能,但它可以完成工作:

function diff_date($start_date, $end_date) {
  list($start_year, $start_month, $start_day) = explode('-', $start_date);
  list($end_year, $end_month, $end_day) = explode('-', $end_date);

  $month_diff = $end_month - $start_month;
  $day_diff   = $end_day - $start_day;

  $months = $month_diff + ($end_year - $start_year) * 12;
  $days = 0;

  if ($day_diff > 0) {
    $days = $day_diff;
  }
  else if ($day_diff < 0) {
    $days = $end_day;
    $months--;

    if ($month_diff > 0) {
      $days += 30 - $start_day;

      if (in_array($start_month, array(1, 3, 5, 7, 8, 10, 12))) {
        $days++;
      }
      else if ($start_month == 2) {
        if (($start_year % 4 == 0 && $start_year % 100 != 0) || $start_year % 400 == 0) {
          $days--;
        }
        else {
          $days -= 2;
        }
      }

      if (in_array($end_month - 1, array(1, 3, 5, 7, 8, 10, 12))) {
        $days++;
      }
      else if ($end_month - 1 == 2) {
        if (($end_year % 4 == 0 && $end_year % 100 != 0) || $end_year % 400 == 0) {
          $days--;
        }
        else {
          $days -= 2;
        }
      }
    }
  }

  return array($months, $days);
}

list($months, $days) = diff_date('1984-05-26', '2010-04-29');

print $months . ' months and ' . $days . ' days old.';

输出:

314个月零3天。


编辑:我试图摆脱代码中的冗余,忘记重命名变量。此功能现在可以正常用于diff_date('2010-06-29', '2011-07-01').


编辑:现在可以在 31 天或 28/29 天后的月份正确工作。

于 2010-07-29T10:39:20.667 回答
0

使用您最喜欢的日期解析函数(strtotime、strptime、mktime)来获取日期之外的 UNIX 时间戳,然后是间隔($now - $then)......然后计算出一个月中有多少秒并使用计算这个人已经活了多少个月(除法和余数是你的朋友)。

这将为您提供一个数学上精确的值,该值也应该足够接近现实生活。

于 2010-07-29T09:42:48.273 回答