简体   繁体   中英

PHP: How to get a Date when a person reach to a specific age?

I am working on task in which dates are involved. I have a person's age in months+days . Now I want to get a date when this person reach to a specific age in months.

For example:

A person is 250 months and 15 days old on 2010-1-25.
On which date this person will become 300 months old? 

Function Signature may be:

function getReqDate( $startDate, $currAgeMonths, $currAgeDays, $reqAgeMonths  ) {
      //return date
}

Since you calculate the current age from the birthdate, I suggest you also use the birthdate instead of the current age to calculate when a user gets 300 months old. The following is the equivalent of the DateTime solution given above (does not require 5.3):

echo date('r', strtotime('+300 months', strtotime('1990-10-13')));

With the second param being the birthdate timestamp the above would give

Tue, 13 Oct 2015 00:00:00 +0200

Further reading:

$date = new DateTime('1990-10-13');
$date->add(new DateInterval('P300M'));
echo $date->format('r');

See DateInterval to see how you write the interval. Again, PHP 5.3.0+ required.

Use the php strtotime function you can get the date you are looking for. eg

strtotime('+50 months', mktime());
function getReqDate( $startDate, $currAgeMonths, $currAgeDays, $reqAgeMonths  ) {
      $unixStartDate = strtotime($startDate);
      $dateBirth = strtotime("-$currAgeDays months", strtotime("-$currAgeMonths months", $unixStartDate));
      return strtotime("+$reqAgeMonths months", $dateBirth);
}
function getReqDate($startDate, $reqAgeMonths ) {
  list($year,$month,$day) = explode('-',$startDate);
  $date = date("Y-m-d", mktime(12, 0, 0, $month+$reqAgeMonths, $day, $year ));
  return $date
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM