IMB
IMB

Reputation: 15889

Add relative time to timestamp that results in same date?

// to simplify $timestamp in this example is the unix timestamp of 2016-04-20

Consider this example:

strtotime('+1 year', $timestamp); // this returns 2017-04-19

How can I make it return 2017-04-20?

Another example:

strtotime('+1 month', $timestamp); // this returns 2016-05-19

How can I make it return 2016-05-20?

Basically, I want to relatively add time that ends up with the same date.

Upvotes: 0

Views: 106

Answers (3)

Mikey
Mikey

Reputation: 2704

I may be misunderstanding what you're asking but you're probably better of using the DateTime library built into PHP, it's a lot more flexible than the standard date() function.

So you could do:

$d = new DateTime();
$d->modify('+1 year');

echo $d->format('Y-m-d'); // Outputs: 2017-04-20

If you want to create a DateTime object from a specific date you can do so by:

$d = DateTime::createFromFormat('Y-m-d', '2016-01-01');
echo $d->format('Y-m-d'); // Outputs 2016-01-01

I believe that's what you're after, it's much cleaner than date() and easier to read in my personal opinion.

Upvotes: 1

Nullsig
Nullsig

Reputation: 38

$date = date("Y",$timestamp) + 1 //gives you the next year

$date .= "-" . date("m-d",$timestamp) //concantenates on the current month and day

Upvotes: 1

Tudor Constantin
Tudor Constantin

Reputation: 26861

strtotime('+1 day', strtotime('+1 year', $timestamp));

?

Upvotes: 1

Related Questions