类似这个问题,但是我的具体问题没有答案。
当前日期为2011-12-14,以备将来查看此问题时参考。
我试过了:
$maxAge = $row['maxAge']; // for example, $row['maxAge'] == 30
$cutoff = date('Y-m-d', strtotime('-$maxAge days'));
对于$cutoff: 1969-12-31
我试了这个:
$maxAge = $row['maxAge']; // for example, $row['maxAge'] == 30
$cutoff = date('Y-m-d', strtotime('-' . $maxAge . ' days'));
对于$cutoff: 2011-03-14
我怎样才能成功地将这个变量传递到strtotime()
函数中,以便它正确地计算要减去的天数?
例如,$maxAge == 30
当前日期是2011-12-14,那么$cutoff
应该是2011-11-14
使用双引号:
date('Y-m-d', strtotime("-$maxAge days"));
使用双引号:
$cutoff = date('Y-m-d', strtotime("-$maxAge days"));
然而,如果你在做这样的简单计算,你可以通过不使用strtotime来简化你的代码,像这样:
$date = getdate();
$cutoff = date('Y-m-d', mktime( 0, 0, 0, $date['mon'], $date['mday'] - $maxAge, $date['year']));
echo $cutoff;
在PHP中,您可以使用双引号或heredoc字符串来扩展变量。单引号和nowdoc字符串不扩展变量。
http://www.php.net/manual/en/language.types.string.php language.types.string.parsing