Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a Variable in strtotime() function in PHP

Similar to this question, but there was no answer to my specific issue.

The current date is 2011-12-14, for reference in case this question is viewed in the future.

I tried this:

$maxAge = $row['maxAge']; // for example, $row['maxAge'] == 30
$cutoff = date('Y-m-d', strtotime('-$maxAge days'));

And it returns the following value for $cutoff: 1969-12-31

And I tried this:

$maxAge = $row['maxAge']; // for example, $row['maxAge'] == 30
$cutoff = date('Y-m-d', strtotime('-' . $maxAge . ' days'));

And it returns the following value for $cutoff: 2011-03-14

How can I pass this variable successfully into the strtotime() function so that it calculates the amount of days to subtract correctly?

For example, if $maxAge == 30 and the current date is 2011-12-14, then $cutoff should be 2011-11-14

like image 585
Oneag Avatar asked Dec 14 '11 16:12

Oneag


People also ask

How does Strtotime work in PHP?

The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT). Note: If the year is specified in a two-digit format, values between 0-69 are mapped to 2000-2069 and values between 70-100 are mapped to 1970-2000.

How do I use Strtotime?

If you want to use the PHP function strtotime to add or subtract a number of days, weeks, months or years from a date other than the current time, you can do it by passing the second optional parameter to the strtotime() function, or by adding it into the string which defines the time to parse.


2 Answers

Use double quotes:

date('Y-m-d', strtotime("-$maxAge days"));
like image 149
samxli Avatar answered Sep 27 '22 21:09

samxli


Use double quotes:

$cutoff = date('Y-m-d', strtotime("-$maxAge days"));

However, if you're doing simple calculations like this, you can simply your code by not using strtotime, like so:

$date = getdate();
$cutoff = date('Y-m-d', mktime( 0, 0, 0, $date['mon'], $date['mday'] - $maxAge, $date['year']));
echo $cutoff;
like image 40
nickb Avatar answered Sep 27 '22 22:09

nickb