linuxoid
linuxoid

Reputation: 1447

PHP: why year not subtracted from date?

The below code doesn't subtract 1 year from the date. Why?

$date1 = '2021-06-02';
$date2 = new \DateTime(date($date1, strtotime('-1 year')));
echo $date2->format('Y-m-d'); // outputs the same date 2021-06-02

Upvotes: 0

Views: 52

Answers (3)

Anand Pandey
Anand Pandey

Reputation: 2025

Please use this code. Its always works for me.

$date1 = '2021-06-02';
$date2 = date("Y-m-d", strtotime("-1 year", strtotime($date1)));
echo $date2; //Output 2020-06-02

This is for Date time object:

$dt = new DateTime('2021-06-02');
$minusOneYearDT = $dt->sub(new DateInterval('P1Y'));
$minusOneYear = $minusOneYearDT->format('Y-m-d');    
echo $minusOneYear;

OR make a small solution:

$time = new DateTime('2021-06-02');
$newtime = $time->modify('-1 year')->format('Y-m-d');
echo $newtime;

Upvotes: 0

IMSoP
IMSoP

Reputation: 97898

Your code is a bit of a muddle:

  • date() takes as parameters a format string, and an integer representing a point in time; it then applies the format to create a string for that date and time
  • strtotime() takes a string, interprets it as a point in time, and returns an integer timestamp
  • new DateTime() takes a string, in any of the formats strtotime would accept, but creates an object representation rather than returning an integer

You've tried to use all of them at once, and got in a mess:

  • Your call to date() has a first parameter of '2021-06-02', which isn't a valid format.
  • Your call to strtotime() has a parameter of '-1 year', which will just be interpreted as "1 year before now", not relative to anything else you've specified.
  • Using both of those functions and then passing to new \DateTime() doesn't make a lot of sense, since the object can do all the same things those functions can do.

If you want to use the integer-based functions, you could write this:

$date1 = '2021-06-02';
$date2 = strtotime("$date1 -1 year");
echo date('Y-m-d', $date2); 

If you want to use the object-based functions, you could write this:

$date1 = '2021-06-02';
$date2 = new \DateTime("$date1 -1 year");
echo $date2->format('Y-m-d'); 

Or this (note the use of DateTimeImmutable instead of DateTime to avoid the modify method changing the $date1 object:

$date1 = new \DateTimeImmutable('2021-06-02');
$date2 = $date1->modify('-1 year');
echo $date2->format('Y-m-d'); 

Upvotes: 0

Schleis
Schleis

Reputation: 43750

Part of your problem is that the date function's first argument is the format of the date.

https://www.php.net/manual/en/function.date.php

So what is happening is that you are creating a date string with the format of '2021-06-02'.

https://www.php.net/manual/en/datetime.format.php

This doesn't use anything from the timestamp that you are providing so this string is passed to the constructor of DateTime and creating the date instead of the one from the year previous.

Upvotes: 1

Related Questions