trafalgar
trafalgar

Reputation: 736

Add efficiently 1 month to current date in CakePHP 2.x

What is the best way to add an expiry date in CakePHP?

I've got an "expiry date" column in my database, I want to add 1 month to the current date, and store this. At the moment, I'm just using strings and plain PHP date functions to create a new date string to save:

$date = date("Y-m-d");
$date = strtotime(date("Y-m-d", strtotime($date)) . " +31 days");
$this->data['Access']['expires'] = $date;

Is there a "more CakePHP" way or efficient/performance wise?

Upvotes: 0

Views: 543

Answers (2)

Marianela Diaz
Marianela Diaz

Reputation: 99

Better that adding 31 days is better to use 1 months this will add 30 or 31 days depending on which month will be the current date

$dateAfterOneMonth = date('Y-m-d H:i:s', CakeTime::fromString('+1 months'))

PrintScreenShoot of Evaluate console in phpstorm

Upvotes: 0

ndm
ndm

Reputation: 60453

Performance wise we're most probably talking about micro optimizations at best, so that probably shouldn't be your main concern. However, all the back and forth that you're doing there doesn't make much sense, a single call to strtotime() is all you need, ie

$this->data['Access']['expires'] = strtotime('+31 days');

This will result in a timestamp of "now + 31 days".

The Cake-ish way would be to use the CakeTime class, for example CakeTime::fromString(), like

App::uses('CakeTime', 'Utility');

$this->data['Access']['expires'] = CakeTime::fromString('+31 days');

When passing a string (it also accepts integers and \DateTime instances), this is basically just a wrapper for strtotime(), and an additional mechanism that incorporates the timezone set for your application, so while this will be a little bit slower of course, it might still be wise to use it.

See also

Upvotes: 0

Related Questions