Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add 2 years to date [closed]

Tags:

date

php

datetime

I can't seem to work out why this isn't working.

I may of done this completely wrong but hoping someone can help.

I have a date and I want to add 2 years to that date. When I run my code it only echo's the date I started with.

Does anyone know where I have gone wrong? I want to only use the date in $start_date not today's date.

$start_date = "2013-05-06 13:18:56";
    $targetDate = date($start_date, strtotime('+2 Years'));
    echo $targetDate;
like image 546
Aaron Avatar asked Dec 20 '22 06:12

Aaron


2 Answers

You want this:

$new_date = date('Y-m-d H:i:s', strtotime('+2 years', strtotime($from_date)));

For the options for the date format, check out the documentation.

like image 182
Paolo Bergantino Avatar answered Dec 30 '22 07:12

Paolo Bergantino


Another option for you is to use the DateTime classes built into PHP:-

$date = \DateTime::createFromFormat('Y-m-d H:i:s', "2013-05-06 13:18:56");
var_dump($date);
$interval = new DateInterval('P2Y');
$date->add($interval);
var_dump($date);

The output from this is something like:-

object(DateTime)[1]
  public 'date' => string '2013-05-06 13:18:56' (length=19)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Europe/London' (length=13)
object(DateTime)[1]
  public 'date' => string '2015-05-06 13:18:56' (length=19)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Europe/London' (length=13)
like image 36
vascowhite Avatar answered Dec 30 '22 05:12

vascowhite