开发者

PHP date of birth checker

开发者 https://www.devze.com 2023-04-06 07:26 出处:网络
I am currently using the following PHP code to check date of birth, the code uses the american mm/dd/yyyy although I\'m trying to change it to the british dd/mm/yyyy.

I am currently using the following PHP code to check date of birth, the code uses the american mm/dd/yyyy although I'm trying to change it to the british dd/mm/yyyy.

I was hoping someone could tell me what to change:

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.";


the explode is breaking up the string into an array, it is using the / as the separator.

So for us dates you would get

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

what you want is to swap the values at index 0 and 1.

try this:

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

Edit, added correction from comment: also change the last line to

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


If you only need a function to return the years given the birthday on that specific format you could use something like this to avoid passing much data on the function call:

<?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.";
?>


It will be better to use timestamp when saving dates.

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

It will give you a better control as the format is always in seconds. It is also easy to format to any date format, sort and perform calculations.

echo date("m/d/Y", 1316631603);             // as US format (09/21/2011)
echo date("d/m/Y", 1316631603);             // as British and Danish format (21/09/2011)

If you choose to use timestamp the answer to your question is:

$user_bdate = date_create_from_format("m/d/Y", "11/30/1978")->format('U'); // Convert a US date to timestamp

$time_diff = time() - $user_bdate; // Take current date and subtract the birth date

echo (int) ($time_diff / (365 * 24 * 60 * 60)) . " years."; // 43 years.

Referrer:

  • php - What is a Unix timestamp and why use it? - Stack Overflow
  • PHP: time - Manual
  • PHP: date - Manual
  • PHP: date_create_from_format - Manual
0

精彩评论

暂无评论...
验证码 换一张
取 消