【问题标题】:How to find date differences in php [duplicate]如何在php中查找日期差异[重复]
【发布时间】:2011-11-10 17:49:49
【问题描述】:

可能重复:
PHP calculate person's current age

我想知道这些人的年龄。

 $time=$row['date_of_birth'];
 $date=explode("-", $time);//gets the date birth from the database and puts it into an array
 $a=getdate();//gets todays date
 $diff_date= gregoriantojd($a["mon"],a["mday"],a["year"] ) - gregoriantojd(date[1],date[2],date[0]);//subtracts the differences between the dates, this is returned in seconds..

问题是这是否是这样做的方法?以及如何转换秒并将它们转换为年(作为整数)?!

编辑: 我认为最后一行应该是这样的:

 return floor($diff_date /60*60*24*365);

【问题讨论】:

  • 返回层($diff_date /60*60*24*365);最后一行应该是那个吗?

标签: php mysql time


【解决方案1】:

试试strtotime(将日期字符串转换为时间戳):

$time = strtotime($row['date_of_birth']);
$age  = date('Y', $time - time());

echo 'age: ' . $age;

【讨论】:

  • 它会给我一个整数还是一个小数?
  • @WithFlyingColors 它会给你一个整数值。
【解决方案2】:

如果 $time 应该是 unix 时间戳

$time=$row['date_of_birth'];
$date1 = new DateTime($time);
$date_diff = $date1->diff(new DateTime(), true);
$age = $date_diff->y;

【讨论】:

    【解决方案3】:

    我认为你可以在 PHP 中使用date_diff 函数。

    【讨论】:

    • 老兄,我想看看我的方法是否有效
    • 如果你想看看你的方法是否有效,然后运行它看看?如果没有,请尝试这些已提供给您的答案。
    【解决方案4】:

    第一个问题:问题是这样做是否可行?

    没有。 gregoriantojd 函数(根据手动条目here)返回一个以天为单位的值,而不是秒。我喜欢 Piotr 提供的最好的 date_diff 转换。

    第二个问题:如何转换秒并将它们转换为年 (作为整数)?!

    好吧,如果你从几秒开始(你不是),那么你的第二个公式大部分是正确的,但它当然不会考虑闰年。因此,对于 4 岁以上或至少 8 岁以上的任何人,它会在他们生日前后关闭一天或多天。通常在他们的生日是一个非常重要的时间来纠正他们的年龄。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-29
      • 2016-07-11
      • 2012-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-28
      相关资源
      最近更新 更多