当前位置: 动力学知识库 > 问答 > 编程问答 >

php - Calculate age from datebirth sql field?

问题描述:

This is the query I am using and it is in page 1 not inside the function.

<?php

$sql2= mysql_query("SELECT *

FROM catego WHERE category_id = '$idc'");

$categoryCount = mysql_num_rows($sql2);

if ($categoryCount>0 )

{

$row2 = mysql_fetch_array($sql2);

$id = $row2["category_id"];

$birthdate = $row2["birthdate"];

$address = $row2["address"];

}

?>

网友答案:

A simple php function could be something like the following:

function birth_date ($birth_date){
    list($y,$m,$d) = explode(",",$birth_date);
    $y_diff  = date("Y") - $y;
    $m_diff = date("m") - $m;
    $d_diff   = date("d") - $d;
    if ($m_diff < 0 || $d_diff < 0) { $y_diff--; }
    return $y_diff;
}

i.e split on your commas, work out the differences, adjust for which side of their birthdate the day/month is, if so reduce the year by one, then just return the year.

Then in your page you can put:

<li><span class="label">Age:</spa><?php$age = getage($birthdate); echo $age;?> </li>

EDIT:

<?php
function birth_date($birth_date){
    list($y,$m,$d) = explode(",",$birth_date);
    $y_diff  = date("Y") - $y;
    $m_diff = date("m") - $m;
    $d_diff   = date("d") - $d;
    if ($m_diff < 0 || $d_diff < 0) { $y_diff--; }
    return $y_diff;
}

$sql2= mysql_query("SELECT * FROM catego WHERE category_id = '$idc'");
$categoryCount = mysql_num_rows($sql2); 
if ($categoryCount>0 )
{
    $row2 = mysql_fetch_array($sql2);     
    $id = $row2["category_id"];
    $birthdate = $row2["birthdate"];
    $address = $row2["address"];

    $age = birth_date($birthdate);
}
?>
网友答案:
SELECT YEAR(SUBDATE(NOW(), INTERVAL DATE_FORMAT("1975,09,02", "%Y-%m") YEAR_MONTH)) fs_age;
网友答案:

In PHP, there are a few ways to do this. Here are some good resources:

http://snippets.dzone.com/posts/show/1310

http://www.dreamincode.net/forums/topic/19953-calculating-age-tutorial/

网友答案:

Like this, in your language of choice:

function getAge(dateOfBirth)
{
DateTime now    = DateTime.Today;

int years   = now.Year - dateOfBirth.Year;
// subtract another year if we're before the birth day in the current year

if (now.Month < dateOfBirth.Month || (now.Month == dateOfBirth.Month && now.Day < dateOfBirth.Day))
 --years;

    return years;
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: