如何在PHP中找到日期差异

时间:2011-11-10 08:53:40

标签: php mysql time

  

可能重复:
  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);

4 个答案:

答案 0 :(得分:3)

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

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

echo 'age: ' . $age;

答案 1 :(得分:1)

如果$time应该是unix时间戳

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

答案 2 :(得分:0)

我认为您可以使用PHP中的date_diff函数。

答案 3 :(得分:0)

  

第一个问题:问题是这是否是这样做的方式?

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

  

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

好吧,如果你从几秒钟开始(你不是这样),那么你的第二个公式大多是正确的,但当然它不会占闰年。因此,对于年龄超过4岁或至少8岁的人来说,在他们的生日周围休息一天或多天。通常在他们的生日是一个非常重要的时间来确保他们的年龄。