n_starnes
n_starnes

Reputation: 376

Add days to date variable

I am trying to add days and/or weeks to a date that is being pulled from a database. All I am getting is the 12-31-1969 default date when it cannot output correctly. Here is my code:

$lastFeed = "6-25-2013"; //pulled from database last feed date 

$feedSchedule = "2"; //pulled from database number of weeks.

$nextFeeding = date("m-d-Y", strtotime($lastFeed . ' + ' . $feedSchedule. ' week'));

I have also tried multiplying the days times the $feedSchedule variable and replacing week(s) with day(s).

Upvotes: 0

Views: 781

Answers (2)

amaster
amaster

Reputation: 2163

Here is code that will work and account for the invalid Date Time String

function nextFeeding($lastFeed,$feedSchedule){
  //fix date format
  $correctedDate = explode("-",$lastFeed);
  //pad month to two digits may need to do this with day also
  if($correctedDate[0] < 10 && strlen($correctedDate[0])!==2){
    $correctedDate[0] = "0".$correctedDate[0];
  }
  $correctedDate = $correctedDate[2]."-".$correctedDate[0]."-".$correctedDate[1];
  //get the next feeding date
  $nextFeeding = date("m-d-Y", strtotime($correctedDate . ' + ' . $feedSchedule. ' week'));
  //return value
  return $nextFeeding;
}

$lastFeed = "6-25-2013"; //pulled from database last feed date 

$feedSchedule = "2"; //pulled from database number of weeks.

$nextFeeding = nextFeeding($lastFeed,$feedSchedule);
echo $nextFeeding;

returns

07-09-2013

Upvotes: 0

php_nub_qq
php_nub_qq

Reputation: 16055

6-25-2013 is not a valid date format. Try YYYY-MM-DD

Upvotes: 2

Related Questions