PHP出生日期检查员

时间:2011-09-21 18:43:33

标签: php

我目前正在使用以下PHP代码来检查出生日期,代码使用美国mm / dd / yyyy,尽管我正在尝试将其更改为英国dd / mm / yyyy。

我希望有人能告诉我要改变什么:

function dateDiff($dformat, $endDate, $beginDate)
{
    $date_parts1=explode($dformat, $beginDate);
    $date_parts2=explode($dformat, $endDate);
    $start_date=gregoriantojd($date_parts1[0], $date_parts1[1], $date_parts1[2]);
    $end_date=gregoriantojd($date_parts2[0], $date_parts2[1], $date_parts2[2]);
    return $end_date - $start_date;
}

//Enter date of birth below in MM/DD/YYYY
$dob="04/15/1993";
echo round(dateDiff("/", date("m/d/Y", time()), $dob)/365, 0) . " years.";

3 个答案:

答案 0 :(得分:1)

爆炸将字符串分解为数组,它使用/作为分隔符。

所以对于我们约会你会得到

$date_parts1[0] = 04
$date_parts1[1] = 15
$date_parts1[2] = 1993

你想要的是交换索引0和1的值。

试试这个:

$start_date=gregoriantojd($date_parts1[1], $date_parts1[0], $date_parts1[2]);
$end_date=gregoriantojd($date_parts2[1], $date_parts2[0], $date_parts2[2]);

编辑,添加了评论更正 也将最后一行改为

echo round(dateDiff("/", date("d/m/Y", time()), $dob)/365, 0) . " years.";

答案 1 :(得分:1)

可以将其转换为使用unix时间戳

echo time();
1316631603 (- Mumber of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT))

它将有更好的控制。

echo date("Y-m-d H:i:s", '1316631603');
2011-09-21 21:00:03

echo date("d-m-Y H:i:s", '1316631603');
21-09-2011 21:00:03

所以问题的答案很简单:

$user_bdate = strtotime("11/30/".date('Y')); // My birthday - Output: 1322607600
$time_to_bdate = $user_bdate-time(); // Take the current date and drag it from my birthday gives x seconds
// Include people who have a week to the birthday and to exclude them after one day
if($time_to_bdate >= -86400 && $time_to_bdate <= 604800) // 86400 seconds in a day - 604800 seconds in a week
{
    echo 'Happy birthday';
}

引荐:

http://php.net/manual/en/function.time.php

http://www.php.net/manual/en/function.date.php

http://www.php.net/manual/en/function.strtotime.php

答案 2 :(得分:1)

如果您只需要一个函数来返回特定格式的生日年份,您可以使用类似的东西来避免在函数调用上传递太多数据:

<?php
    function get_age($birthdate){
        list($d, $m, $y) = explode('/', $birthdate);
        $time_birth =  mktime(0, 0, 0, $m, $d, $y);
        return round( (time() - $time_birth) / (60*60*24*365) ) ;
    }

    //example, use dd/mm/yyyy
    $dob="04/15/1993"; 
    echo get_age($dob). " years.";
?>