0

I have found several posts regarding this topic but I cannot get my function to work. If the amount of days to add > 0, the returning date = 70-01-01

Example: $date='12-07-11' $days='5'

Should return 17-07-11 instead of 70-01-01
I need to use the variables because $date and $days are results from an oracle query.

function addDayswithdate($date,$days)
{
  $originalDate = $date;
  $newDate = date("y-m-d", strtotime($originalDate));

  if ($days>0)
  {
    $var="+". $days ." days";
    $date = strtotime($var, strtotime($newDate));
  }

  $originalDate = $date;
  $newDate = date("y-m-d", strtotime($date));

  return $newDate;
}
Albzi
  • 15,431
  • 6
  • 46
  • 63

5 Answers5

4

Use Datetime::createFromFormat and DateInterval

$date = DateTime::createFromFormat('d-m-y','12-07-11');
$date->add(new DateInterval('P5D'));
echo $date->format('d-m-Y') . "\n";
Abhik Chakraborty
  • 44,654
  • 6
  • 52
  • 63
  • Thanks, I have changed it to this and it is working! $date = DateTime::createFromFormat('d-m-y',$_date); $date->add(new DateInterval('P'. $days . 'D')); return $date->format('d-m-Y') . "\n"; – Mascha Oostenbrug Apr 10 '14 at 11:23
  • Now this is the answer I was looking for. I have got date saved as string but every other answer on similar questions on stack overflow assumes that date is in date format! There are many such questions and your answer should definitely come at the top of all. Thanks. – gegobyte Feb 05 '16 at 10:25
0

Why not keep it simpler?

function addDays($date, $days)
{
   $time = strtotime($date);
   $new_time = $time + (86400 * $days) //86400 seconds per day
   return $new_time;
}
Ben Poulson
  • 3,368
  • 2
  • 17
  • 26
0

Why not do it like this:

echo date('Y-m-d', strtotime($date + $days .'days'));
InsaneSVK
  • 206
  • 2
  • 3
  • 10
0
function addDays($date, $days)
{
    $date_uts = strtotoime($date);
    $add_days = $days*86400;

    $final_date = date('Y-m-d', $date_uts+$add_days);
    return $final_date;
}
Parag Tyagi
  • 8,780
  • 3
  • 42
  • 47
  • If $date = 23-06-11 and $days = 1, the returning value is 2023-06-12. Not correc. Should be 24-06-11 – Mascha Oostenbrug Apr 10 '14 at 11:12
  • Assuming that days always have 86400 seconds is like assuming months always have 30 days, except that the error is harder to spot. Don't get into this path: date calculations are hard, let the computer do them for you. – Álvaro González Apr 10 '14 at 11:19
0

In addition of using vanilla php DateTime class, you can use Carbon if you have to work often with dates.

Carbon let you do anything like this

$date = Carbon::now()->addDays(5);
Fed03
  • 575
  • 5
  • 16