11/26/2013

Create one negative DateInterval Object with DateTime

If you want to create one negative DateInterval, you may use the following ways

Get dateTime object two months ago.

$dateTime = (new DateTime());
var_dump($dateTime);

$month = -2;
$dateInterval = new DateInterval('P' . abs($month) . 'M');
 if ($month < 0) {
       $dateInterval->invert = 1;
 }
$dateTime->add($dateInterval);

it will shows:

object(DateTime)[94]
  public 'date' => string '2013-11-26 11:10:23' (length=19)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Asia/Tokyo' (length=10)

object(DateTime)[94]
  public 'date' => string '2013-09-26 11:10:23' (length=19)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Asia/Tokyo' (length=10)

No comments:

Post a Comment